<?php

namespace app\mp\admin;

use app\common\service\DistributingFeed as DistributingFeedService;
use app\common\service\GeneralMaterial as GeneralMaterialService;
use app\common\service\Material as MaterialService;
use app\common\service\MaterialReturn as MaterialReturnService;
use app\common\service\MaterialStock as MaterialStockService;
use app\common\service\MaterialStockUse as MaterialStockUseService;
use app\common\service\Memo as MemoService;
use app\common\service\Order as OrderService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\Purchasing as PurchasingService;
use app\common\service\Sku as SkuService;
use app\common\service\StallFeed as StallFeedService;
use app\common\service\Stock as StockService;
use app\common\service\StockLog as StockLogService;
use app\system\admin\Admin;
use Endroid\QrCode\QrCode;
use think\Db;

/**
 * 物料进度
 */
class PurchasingV2 extends Admin
{

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 物料进度
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/3
     */
    public function index()
    {
        $stat = $this->request->param('a/s', '');
        $action=$this->request->param("action");
        $labelid= $this->request->param('labelid/d', 0);
        if($action=='refreshSearchLabels'){
            $labelstr = $this->_showSearchLabels();
            $result = [
                'code' => 0, 'msg' => 'success','labelstr'=>$labelstr,
            ];
            return json($result);
        }
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $export = $this->request->param('export/d', 0);
            if($stat=='searchLabel'){
                list($where, $whereRaw, $whereHaving, $sql_leftjoin_order_material, $where_material_property) = $this->_searchLabelWhere($labelid);
            }else{
                list($where, $whereRaw, $whereHaving, $sql_leftjoin_order_material, $where_material_property) = $this->_where_index();
            }
            if ($export) {
                set_time_limit(0);
                $page = 1;$limit = 99999;
            }

            //订单加一级
            order_level($where, 'o.');
            $order = "o.caigou_status asc,o.id desc";
            $list = db('order o')
                ->field("o.id,o.ext_id,o.client_ordernum,o.`status`,o.sku,o.is_auto_import,o.o_type,o.type,o.type_ext
                ,o.factory_id,o.quantity
                ,o.shipment_time,o.over_time,o.create_time,o.caigou_over_time,o.caichuang_over_time
                ,o.chejian_over_time,o.tail_over_time
                ,o.caigou_status,o.caigou_user_id,su.nick as caigou_user_name,o.caigou_remark,o.remark_approval_color
                ,o.outgo_status,ftout.name as factory_outgo_name
,s.pic,s.ori_pic 
,ft.name as factory_name,g.name as group_name
,group_concat(distinct os.mid,',', os.size_name,',',os.order_count ,',',os.shicai_count,',',os.jiaohuo_count,',',os.jiaohuo_tail_count,',',os.delivery_count,',',os.daohuo_count  SEPARATOR ';') as order_size_list
,min(om.caigou_show) as  caigou_show_min ,max(om.caigou_show) as caigou_show_max
,min(om.caigou_status) as caigou_status_min,max(om.caigou_status) as caigou_status_max
,min(om.tiaoshu) as tiaoshu_min ,max(om.tiaoshu) as tiaoshu_max
,min(om.is_caigou_start) as is_caigou_start_min
")
                ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
                ->join('factory ft', "o.factory_id=ft.id", 'left')
                ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
                ->join('group g', "o.group_id=g.id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size os ', 'o.id=os.order_id', 'left')
                ->join('system_user su', "o.caigou_user_id=su.id", 'left')
                ->join('material m', "om.material_id=m.id", 'left')
                ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
                ->where($where)
                ->whereRaw($whereRaw)
                ->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')
                ->having($whereHaving)
//                ->fetchSql(true)
                ->select();
            //echo lastsql();die;
            $count = db('order o')
                ->join('factory ft', "o.factory_id=ft.id", 'left')
                ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
                ->join('group g', "o.group_id=g.id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size os ', 'o.id=os.order_id', 'left')
                ->join('system_user su', "o.caigou_user_id=su.id", 'left')
                ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
                ->join('material m', "om.material_id=m.id", 'left')
                ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
                ->where($where)
                ->whereRaw($whereRaw)
                ->group('o.id')
                ->having($whereHaving)
                ->count();
            $skuService = new SkuService();
            $order_id_array = [];
            foreach ($list as $k => $v) {
                $list[$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
                $list[$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
                $list[$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
                $list[$k]['osList'] = $osList = $this->_deal_order_size_list($v['order_size_list']);
                $list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
                $list[$k]['skuStock'] = $skuService->getSkuStockBySku($v['sku'], $v['factory_id']);
                $list[$k]['ext_id'] = trim($list[$k]['ext_id']);
                $list[$k]['factory_name'] = trim($list[$k]['factory_name']);
                $list[$k]['group_name'] = trim($list[$k]['group_name']);
                $order_id_array[] = $v['id'];
            }
            $list_order_material = db('order_material om')
                ->field("om.mid,om.material_id,om.order_id,om.client_ordernum,om.fabric_width,om.weight
                ,om.material_dosage,om.loss,om.caigou_status,om.factory_id
                ,om.is_make_tag,om.is_caigou_start,om.need_checkcloth,om.need_shrink
                ,om.caigou_unitprice,om.shiji_caigou_count,om.tiaoshu,om.tiaoshu_detail,om.tiaoshu_status,om.return_length
                ,om.arrive_time,om.arrive_time_first,om.caigou_over_time
                ,om.send_goods_status
                ,m.name,m.type,m.material_sku,m.model,m.colornum,m.color,m.supplier,m.address,m.contact
                ,m.purchasing_unit
                ,sum(IF(sl.type=0, IFNULL(sl.operate_num, 0),0)) as operate_num_0
                ,sum(IF(sl.type=2, IFNULL(sl.operate_num, 0),0)) as operate_num_2
                ,sum( IFNULL(ms.metre_left, 0) ) as have_metres
                ,sum(IF(msu.status=1, IFNULL(msu.metre, 0),0)) as apply_and_used_0_apply
                ,sum(IF(msu.status=2, IFNULL(msu.metre, 0),0)) apply_and_used_0_used
                ,mi.need_checkcloth as mi_need_checkcloth
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_checkcloth=1 and mi.is_return=0, mi.id,null)) as cloth_0
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_shrink=1 and mi.is_return=0, mi.id,null)) as cloth_1
                
                ,count(IF(mr.status <=1 , 1,null)) as material_return_0
                ,count(IF(mr.is_renew=1 and mr.status <>1 , 1,null)) as material_return_1
                ,count(IF(mr.is_renew=1 , 1,null)) as material_return_2
                ")
                ->join('material m', "om.material_id=m.id", 'left')
                ->join('stock_log sl', "m.type='accessories' and om.material_id=sl.material_id and om.order_id=sl.order_id", 'left')
                ->join('material_stock ms', "om.material_id=ms.material_id and ms.cutting_time=0", 'left')
                ->join('material_stock_use msu', "om.order_id=msu.order_id and om.material_id=msu.material_id", 'left')
                ->join('order_material_item mi', "om.order_id=mi.order_id and om.material_id=mi.material_id", 'left')
                ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
                ->join('order o', "o.id=om.order_id", 'left')
                ->where([
                    ['om.order_id', 'in', $order_id_array],
                    ['om.material_id', '>', 0],
                    ['om.caigou_show', '<>', 0],// 去除不在采购进度显示条目
                ])
                ->where($where_material_property)
                ->order('om.caichuang_standard desc')
                ->group('om.mid')
                ->select();
            $allQuantity = 0;
            $skuCount_array = [];
            foreach ($list as $k => $v) {
                $list[$k]['omList'] = [];
                $list[$k]['approval_color_all'] = 1;// 是否全部批色
                foreach ($list_order_material as $k2 => $sv) {
                    if ($v['id'] == $sv['order_id']) {
                        $sv['jing_material_dosage'] = round($v['quantity'] * $sv['material_dosage'], 2);
                        $sv['total_material_dosage'] = round(($v['quantity'] * $sv['material_dosage']) + ($v['quantity'] * $sv['material_dosage']) * $sv['loss'] / 100, 2);
                        // 余料使用
                        $sv['stock_use_num'] = $sv['operate_num_0'] - $sv['operate_num_2'];
                        // 物料状态
                        $sv['material_status'] = $this->getMaterialStatusV2($sv);
                        $sv['sku'] = $v['sku'];
                        $list[$k]['omList'][] = $sv;
                        $sv['type'] <> 'accessories' && $sv['caigou_status'] != 1 && $list[$k]['approval_color_all'] = 0;
                    }
                }
                $allQuantity += $v['quantity'];
                $skuCount_array[trim($v['sku'])] = 1;
            }
            if ($export) {
                if($count>20000){//
                    echo "<script language='JavaScript'>alert('当前导出数据过大已超过2万条，请筛选后再选择导出');window.close()</script>";die;
                }
                $this->_exportXls('采购进度-' . date('YmdHis'), $list, $stat);
                exit;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
                'page_info' => [
                    'page' => $page,
                    'limit' => $limit,
                ],
                'skuCount' => count($skuCount_array),
                'allQuantity' => $allQuantity,
            ];
            return json($result);
        }
        $factoryKV = getFactoryKV(false);
        $stallsKV = getStallsKV();
        $assign = [
            'labelid' => $labelid,
            'action'    =>$stat,
            'factoryKV' => [0 => '请选择'] + $factoryKV,
            'stallsKV' => [0 => '请选择'] + $stallsKV,
            'orderFrom' => [0 => '请选择'] + config('mimo.order_from'),
            'purchasingUserKV' => [0 => '请选择'] + getTagUserKV('tag_purchasing_user'),
        ];
        if($stat!='searchLabel') { //显示搜索标签
            $labelstr = $this->_showSearchLabels();
            $assign['labelstr'] = $labelstr;
        }
        $labelid= $this->request->param('labelid/d', 0);
        $marerialType=['全部','面料','辅料'];//物料类型
        $materialStatus=[1=>'未采购',2=>'采购中',3=>'换料中',4=>'已到料',5=>'未批色',6=>'批色不通过',7=>'已批色',13=>'未发货',14=>'已发货',8=>'批色已齐套',9=>'批色未齐套',10=>'采购未齐套',11=>'采购已齐套',15=>'发货未齐套',16=>'发货已齐套',12=>'可裁剪']; //搜索物料状态
        $HistoryDate=['all'=>'','today'=>date("Y-m-d"),'yestoday'=>date("Y-m-d",strtotime("-1 day"))];
        if($labelid>0){
            $v= db("search_label")->find($labelid) ;
            $v['material_type']=$marerialType[$v['search_materal_type']];
            list($start_time,$end_time)=$v['search_history']!='all' ?
                [date($HistoryDate[$v['search_history']]." 00:00:00"),date($HistoryDate[$v['search_history']]." ".$v['search_end_time'])] : ['',''];
            $v['time']=$start_time.' - '.$end_time;
            $v['material_status']=$v['search_data_status']=='' ? "" : $this->_getIdstrNames($v['search_data_status'],$materialStatus);
            $v['material_status']=str_replace(',',$v['m_status_logic']=='and'? ',并且' : ',或',$v['material_status']);
            $v['factory_ids_str']=$v['factory_ids']=='' ? "" : $this->_getIdstrNames($v['factory_ids'],[0 => '未分厂']+$factoryKV);
            $assign['labelinfo']=$v;
        }
        return $this->assign($assign)->fetch();
    }

    //返回搜索标签记录数
    private function _getLabelDataCount($labelid){
        list($where, $whereRaw, $whereHaving, $sql_leftjoin_order_material, $where_material_property) = $this->_searchLabelWhere($labelid);
        $count = db('order o')
            ->join('factory ft', "o.factory_id=ft.id", 'left')
            ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
            ->join('group g', "o.group_id=g.id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('order_size os ', 'o.id=os.order_id', 'left')
            ->join('system_user su', "o.caigou_user_id=su.id", 'left')
            ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
            ->join('material m', "om.material_id=m.id", 'left')
            ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
            ->where($where)
            ->whereRaw($whereRaw)
            ->group('o.id')
            ->having($whereHaving)
            ->count();
        //if($labelid>50) dump(lastsql());
        return $count;
    }

    private function _where_index()
    {
        $sql_leftjoin_order_material = "";
        $whereHaving = '1=1';
        $where_material_property = [];// 物料附加条件
        $whereRaw = '1=1 ';
        $where = [
            ["o.status", 'in', [0, 1]],
            ['o.client_status', '<>', 99],
            ['om.caigou_show', '>', 0]
        ];
        $stat = $this->request->param('a/s', '');
        if ($stat == 'stat') {
            $where = [
                ["o.status", 'in', [0, 1, 2]],
                ['o.client_status', '<>', 99],
            ];
        }
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $factorId = $this->request->param('factory_id/d', 0);
        $orderStatus = $this->request->param('order_status/s', '');
        $createDateRange = $this->request->param('create_date_range/s', '');
        $isAutoImport = $this->request->param('is_auto_import/d', 0);
        $type = $this->request->param('type/s', '');
        $out_time_limit = $this->request->param('out_time_limit/d', 0);
        $material_status = $this->request->param('material_status/d', 0);
        $material_property = $this->request->param('material_property_v2/d', 0);
        $arrive_time_status = $this->request->param('arrive_time_status_v2/d', 0);

        $statCondition = $this->request->param('sc/s', '');
        switch (env('env_site')) {
            case 'riwei':
                $ext_id = trim($this->request->param('ext_id'));
                $ext_id != '' && $where[] = ['o.ext_id', '=', $ext_id];
                break;
        }
        if ($clientOrdernum != '') {
            $where[0] = ["1", '=', 1];//清["o.status", 'in', [0, 1]],这个条件
            $where[1] = ["1", '=', 1];
            $where[] = ['o.client_ordernum', '=', $clientOrdernum];
        }
        if ($sku != '') {
            $where[0] = ["1", '=', 1];
            $where[1] = ["1", '=', 1];
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($factorId) {
            $where[] = ['o.factory_id', '=', $factorId];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($isAutoImport > 0) {
            $where[] = ['o.is_auto_import', '=', $isAutoImport];
        }
        if ($type != '') {
            switch ($type) {
                case 'my_return_first'://返单第一次
                    $where[] = ['o.type_ext', '=', $type];
                    break;
                default:
                    $where[] = ['o.type', '=', $type];
                    break;
            }
        }
        if ($out_time_limit > 0) {
            $where[] = ['o.caigou_status', '=', 0];
            switch ($out_time_limit) {
                case 3:
                case 5:
                case 8:
                    $where[] = ['o.create_time', '<=', time() - $out_time_limit * 24 * 3600];
                    break;
            }
        }
        if ($orderStatus != '') {//放到最后，这样查询才快点
            $where[] = ['om.caigou_show', '<>', 0];
            $where[] = ['o.stock_type', 'not in', '10,11'];

            switch ($orderStatus) {
                case 1:    // 面料采购未完成（未打标）
                    $where[] = ['m.type', '<>', 'accessories'];
                    $where[] = ['om.is_make_tag', '=', 0];
                    break;
                case 2:    //辅料采购未完成（未打标）
                    $where[] = ['m.type', '=', 'accessories'];
                    $where[] = ['om.is_make_tag', '=', 0];
                    break;
                case 3: // 换料中
                    $where[] = ['o.status', 'in', [0, 1, 2]];
                    $where[] = ['mr.status', '=', 1];
                    break;
                case 4: // 批色不通过
                    $where[] = ['o.status', 'in', [0, 1, 2]];
                    $where[] = ['om.caigou_show', '=', 1];
                    $where[] = ['om.caigou_status', '=', 2];
                    break;
                case 5: // 面料已到料
                    $where[] = ['o.status', 'in', [0, 1]];
                    $where[] = ['m.type', '<>', 'accessories'];
                    $where[] = ['om.caigou_show', '=', 1];
                    $where[] = ['om.is_make_tag', '=', 1];
                    break;
                case 6: // 已批色
                    $where[] = ['o.status', 'in', [0, 1, 2]];
                    $sql2 = "select min(om2.caigou_status) as caigou_status_min
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories'  ";
                    $sql_leftjoin_order_material = " and 1=({$sql2})";
                    break;
                case 7://未批色  有未点批色按钮
                    $where[] = ['m.type', '<>', 'accessories'];
                    $where[] = ['om.caigou_status', '=', 0];
                    break;
                case 8://未采购  有未点购按钮
                    $where[] = ['om.is_caigou_start', '=', 0];
                    break;
                case 9://采购中  有未点购按钮
                    $where[] = ['om.is_caigou_start', '=', 1];
                    break;
                case 10://辅料已到料
                    $where[] = ['m.type', '=', 'accessories'];
                    $sql = "select min(om2.is_caigou_start) as is_caigou_start_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type='accessories'";
                    $sql_leftjoin_order_material = " and 2=($sql)";
                    break;
                case 11://采购完成 全部批色  打标数>0
//                    $where[] = ['m.type', '<>', 'accessories'];
//                    $whereHaving .= " and caigou_show_min=1 and caigou_show_max=1 ";
//                    $whereHaving .= " and caigou_status_min=1 and caigou_status_max=1  ";
//                    $whereHaving .= " and tiaoshu_min>0 ";
                    $sql = "select min(om2.is_caigou_start) as is_caigou_start_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql2 = "select min(om2.caigou_status) as caigou_status_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories'  ";
                    $sql_leftjoin_order_material = " and ( (2=($sql) and 1=({$sql2})) Or o.caigou_status=1 ) ";
                    $where[0] = ["o.status", 'in', [0, 1, 2]];
                    break;
                case 12://换料中 打标数<0
                    $where[] = ['m.type', '<>', 'accessories'];
                    $where[] = ['om.tiaoshu_status', '=', 10];
//                    $sql0 = "select  count(IF(mr.status <=1 , 1,null)) as material_return_0
//from wx_order_material om2
//left join wx_material_return mr on (om2.mid=mr.order_material_id)
//where o.id=om2.order_id and om2.caigou_show<>0 ";
//                    $sql1 = "select  count(IF(mr.is_renew=1 and mr.status <>1 , 1,null)) as material_return_1
//from wx_order_material om2
//left join wx_material_return mr on (om2.mid=mr.order_material_id)
//where o.id=om2.order_id and om2.caigou_show<>0 ";
//                    $sql2 = "select count(IF(mr.is_renew=1 , 1,null)) as material_return_2
//from wx_order_material om2
//left join wx_material_return mr on (om2.mid=mr.order_material_id)
//where o.id=om2.order_id and om2.caigou_show<>0 ";
//                    $sql_leftjoin_order_material = "  and (0<({$sql0}) or ( ($sql1)<=0 and ($sql2)>0 ))";
                    break;
                case 13:
                    $where[] = ['o.caichuang_can_do', '=', 1];
                    $where[] = ['o.caichuang_status', '=', 0];
                    break;
            }
        }
        if ($statCondition != "") {
            switch ($statCondition) {
                case "allCount":    // 全部
                    break;
                case "fabricCgOverCount":    //面料采购已完成单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    break;
                case "returnMaterialCount":    //退料中

                    $subQuery1 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];
                    break;
                case "fabricCgNotCount": // 面料采购未完成单
                    $where[] = ["o.status", 'in', [0, 1]];
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    break;
                case "apColorOverCount": // 已批色单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                    break;
                case "apColorNotCount": // 未批色单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("in({$subQuery2})")];

                    break;
                case "apColorNoCount": // 批色不通过单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                    $subQuery4 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=2")->distinct(true)->field('om.order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("in({$subQuery4})")];

                    break;
                case "ckClothSkOverCount": // 已验布缩水的单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $subQuery2 = db('order_material_item omi')->join('order_material om', "omi.order_material_id=om.mid", 'left')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and omi.is_return=0 and om.caigou_show=1 and ((om.need_checkcloth=1 and omi.is_checkcloth=0) or (om.need_shrink=1 and omi.is_shrink=0))")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                    break;
                case "ckClothSkNotCount": //未验布缩水的单数=面料采购已完成单-已验布缩水的单数
                    $subQuery1 = db('order_material_item omi')
                        ->join('order_material om', "omi.order_material_id=om.mid", 'left')
                        ->join('material m', "om.material_id=m.id", 'left')
                        ->where("m.type in ('fabric', 'lining') and omi.is_return=0 
                        and om.caigou_show=1 and ((om.need_checkcloth=1 
                        and omi.is_checkcloth=0) or (om.need_shrink=1 and omi.is_shrink=0))")
                        ->distinct(true)
                        ->field('om.order_id')->buildSql();
                    $subQuery2 = db('order_material om')
                        ->join('material m', "om.material_id=m.id", 'left')
                        ->where("m.type in ('fabric', 'lining') and om.caigou_show=1 
                        and om.is_make_tag=0")->distinct(true)
                        ->field('om.order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];
                    $where[] = ['o.status', 'in', [0, 1]];
                    $where[] = ['o.caichuang_can_do', '=', 0];
                    $where[] = ['o.caichuang_status', '=', 0];
                    $where[] = ['om.is_make_tag', '=', 1];
                    $where[] = [' om.tiaoshu', '>', 0];
                    break;
                case "caichuangOverCount": // 已裁床单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                    $where[] = ['o.caichuang_over_time', '<>', 0];

                    break;
                case "caichuangNotCount": ////未裁床单数=批色完成-已裁床单数
//                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
//                    $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
//                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
//                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
//                    $subQuery3 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=2")->distinct(true)->field('om.order_id')->buildSql();
//                    $subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
//                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
//                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery4})")];
                    $where[] = ['o.status', 'in', [0, 1]];
                    $where[] = ['o.caichuang_can_do', '=', 1];
                    $where[] = ['o.caichuang_over_time', '=', 0];
                    $where[] = [' om.tiaoshu', '>', 0];
                    break;
                case "acOverCount": // 辅料发放单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery4})")];
                    $where[] = ['o.caichuang_over_time', '<>', 0];
                    $subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                    break;
                case "acNotCount": // 辅料未发放单数
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                    $subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                    $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery4})")];
                    $where[] = ['o.caichuang_over_time', '<>', 0];
                    $subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("in({$subQuery3})")];
                    break;
                case "acNoCount": //辅料采购未完成
                    $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_caigou_start!=2")->distinct(true)->field('om.order_id')->buildSql();
                    $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];
                    $where[] = ['o.status', 'in', [0, 1]];
                    break;
            }
            $where[] = ['stock_type', 'not in', '10,11'];
        }
        if ($material_status > 0) {
            $where[] = ['o.caichuang_status', '=', 0];
            $where[] = ['o.chejian_status', '=', 0];
            switch ($material_status) {
                case 1://未采购
                    $where[] = ['om.is_caigou_start', '=', 0];
                    $where_material_property[] = ['om.is_caigou_start', '=', 0];
                    break;
                case 2://采购中
                    $where[] = ['om.is_caigou_start', '=', 1];
                    $where_material_property[] = ['om.is_caigou_start', '=', 1];
                    break;
                case 3://换料中
                    $where[] = ['om.tiaoshu_status', '=', 10];
                    $where_material_property[] = ['om.tiaoshu_status', '=', 10];
                    break;
                case 4://已到料 含义：按了到料，不要换料中
                    $where[] = ['om.arrive_time', '>', 0];
                    $where_material_property[] = ['om.arrive_time', '>', 0];
                    $where[] = ['om.tiaoshu_status', '<>', 10];
                    $where_material_property[] = ['om.tiaoshu_status', '<>', 10];
                    break;
                case 13://未发货
                    $where[] = ['om.send_goods_status', '=', 0];
                    $where_material_property[] = ['om.send_goods_status', '=', 0];
                    break;
                case 14://已发货
                    $where[] = ['om.send_goods_status', '=', 1];
                    $where_material_property[] = ['om.send_goods_status', '=', 1];
                    break;
                case 5://未批色
                    $where[] = ['om.caigou_status', '=', 0];
                    $where_material_property[] = ['om.caigou_status', '=', 0];
                    break;
                case 6://批色不通过
                    $where[] = ['om.caigou_status', '=', 2];
                    $where_material_property[] = ['om.caigou_status', '=', 2];
                    break;
                case 7://已批色
                    $where[] = ['om.caigou_status', '=', 1];
                    $where_material_property[] = ['om.caigou_status', '=', 1];
                    break;
                case 8://已批色齐套  不包括：已完成裁床以后的订单
                    $where[] = ['om.caigou_status', '=', 1];
                    $where[] = ['m.type', '<>', 'accessories'];
                    $sql = "select min(om2.caigou_status) as caigou_status_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories' ";
                    $sql2 = "select max(om2.caigou_status) as caigou_status_max
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories' ";
                    $sql_leftjoin_order_material = " and 1=($sql) and 1=($sql2)";
                    break;
                case 9://批色未齐套
                    $where[] = ['om.caigou_status', '<>', 1];
                    $where[] = ['m.type', '<>', 'accessories'];
                    $sql = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' ";
                    $sql1 = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' and om2.caigou_status=1  ";
                    $sql_leftjoin_order_material = " and ($sql1)>0 and 1<($sql)  and ($sql)>($sql1)    ";
                    break;
                case 10://采购未齐套 有一个采购完成
                    $where[] = ['om.is_caigou_start', '<>', 2];
                    $sql = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql1 = "select max(om2.is_caigou_start) as is_caigou_start_max
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql2 = "select min(om2.is_caigou_start) as is_caigou_start_min
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql_leftjoin_order_material = " and 1<($sql)  and 2=($sql1) and 2>($sql2)  ";
                    break;
                case 11://采购已齐套 定义：只要全部物料是“采购完成”状态  或  或中有一个是“可裁剪”+其它全是“采购完成 ”
                    $whereRaw .= " and ( o.caichuang_can_do <> 1 OR o.caichuang_status <>0)";//与12 切开
                    $where[] = ['om.is_caigou_start', '=', 2];
                    $where[] = ['om.tiaoshu_status', '<>', 10];//
                    $sql = "select min(om2.is_caigou_start) as is_caigou_start_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql2 = "select max(om2.is_caigou_start) as is_caigou_start_max
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql3 = "select IFNULL(max(om2.tiaoshu_status), 0) 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.tiaoshu_status=10 ";
                    $sql_leftjoin_order_material = " and 2=($sql) and 2=($sql2) and  10<>($sql3) ";
                    break;
                case 12://可裁剪 与以前的 未裁剪完成一样。
                    $where[] = ['o.caichuang_can_do', '=', 1];
                    $where[] = ['o.caichuang_status', '=', 0];
                    $sql = "select min(om2.caichuang_can_do)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' ";
                    $sql_leftjoin_order_material = " and ($sql)>0";
                    break;
                case 15://发货未齐套 //1与0的互相作用肯定物料数>=2样以上。
                    $where[] = ['om.send_goods_status', '=', 1];
//                    $sql = "select count(0)
//from wx_order_material om2
//left join wx_material m2 on (om2.material_id=m2.id)
//where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql1 = "select min(om2.send_goods_status)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
//                    $sql_leftjoin_order_material = " and 1<($sql)  and 0=($sql1)  ";
                    $sql_leftjoin_order_material = " and 0=($sql1)  ";
                    break;
                case 16://发货已齐套
                    $where[] = ['om.send_goods_status', '=', 1];
                    $sql = "select min(om2.send_goods_status)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql_leftjoin_order_material = " and 1=($sql)  ";
                    break;
            }
        }
        switch ($material_property) {
            case 0://全部
                switch ($material_status) {
                    case 1://未采购
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.is_caigou_start=0 ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 2://采购中
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.is_caigou_start=1 ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 3://换料中
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.tiaoshu_status=10 ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 4://已到料 含义：按了到料，不要换料中
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.arrive_time>0 ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 13://未发货
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.send_goods_status=0 ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 14://已发货
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.send_goods_status=1 ";
                        $sql_leftjoin_order_material .= " and 0<($sql) ";
                        break;
                }
                break;
            case 1://面料
                switch ($material_status) {
                    case 1://未采购
                        $where[] = ['m.type', '<>', 'accessories'];
                        $where_material_property[] = ['m.type', '<>', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.is_caigou_start=0 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 2://采购中
                        $where[] = ['m.type', '<>', 'accessories'];
                        $where_material_property[] = ['m.type', '<>', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.is_caigou_start=1 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 3://换料中
                        $where[] = ['m.type', '<>', 'accessories'];
                        $where_material_property[] = ['m.type', '<>', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.tiaoshu_status=10 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 4://已到料 含义：按了到料，不要换料中
                        $where[] = ['m.type', '<>', 'accessories'];
                        $where_material_property[] = ['m.type', '<>', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.arrive_time>0 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 13://未发货
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.send_goods_status=0 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 14://已发货
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.send_goods_status=1 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 5://未批色
                    case 6://批色不通过
                    case 7://已批色
                        $where[] = ['m.type', '<>', 'accessories'];
                        $where_material_property[] = ['m.type', '<>', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 8:
                    case 9:
                    case 10:
                    case 11:
                    case 12:
                        break;
                }
                break;
            case 2://铺料
                switch ($material_status) {
                    case 1://未采购
                        $where[] = ['m.type', '=', 'accessories'];
                        $where_material_property[] = ['m.type', '=', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.is_caigou_start=0 and m2.type='accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 2://采购中
                        $where[] = ['m.type', '=', 'accessories'];
                        $where_material_property[] = ['m.type', '=', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.is_caigou_start=1 and m2.type='accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                    case 3://换料中
                        $where[] = ['m.type', '=', 'accessories'];
                        $where_material_property[] = ['m.type', '=', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.tiaoshu_status=10 and m2.type='accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 4://已到料 含义：按了到料，不要换料中
                        $where[] = ['m.type', '=', 'accessories'];
                        $where_material_property[] = ['m.type', '=', 'accessories'];
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.arrive_time>0 and m2.type='accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 13://未发货
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.send_goods_status=0 and m2.type='accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 14://未发货
                        $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.send_goods_status=1 and m2.type='accessories' ";
                        $sql_leftjoin_order_material = " and 0<($sql) ";
                        break;
                    case 5:
                    case 6:
                    case 7:
                        $where[] = ['m.type', '=', 'accessories'];
                        $where_material_property[] = ['m.type', '=', 'accessories'];
                        break;
                    case 8:
                    case 9:
                    case 10:
                    case 11:
                    case 12:
                        break;
                }
                break;
        }
        if ($arrive_time_status > 0) {
            switch ($arrive_time_status) {
                case 1://已按过到料
                    $where[] = ['om.arrive_time', '>', 0];
                    $where_material_property[] = ['om.arrive_time', '>', 0];
                    break;
                case 2://没按过到料
                    $where[] = ['om.arrive_time', '=', 0];
                    $where_material_property[] = ['om.arrive_time', '=', 0];
                    break;
            }
        }
        return [
            $where,
            $whereRaw,
            $whereHaving,
            $sql_leftjoin_order_material,
            $where_material_property,
        ];
    }

    /**
     * @return list
     * 显示可以看到的搜索标签
     */
    private function _showSearchLabels(){
        $adminid=ADMIN_ID;
        $user_role=db("system_user_role")->where("user_id=$adminid")->column('role_id');
        $whereOr='';$showAllLabels=false;
        //查询当前帐号可看到的搜索标签, 1超级管理,23supper管理  可查看全部标签
        foreach ( $user_role as $key=>$roleid){
            $whereOr .="FIND_IN_SET(".$roleid.", visit_role_ids) or ";
            $showAllLabels=in_array($roleid,[1,23]) ? true : $showAllLabels;
        }
        $whereOr = " or FIND_IN_SET(".$adminid.", visit_admin_ids)";
        $whereOr=trim($whereOr,' or ');
        $whereOr=$showAllLabels==true ? '' : $whereOr;
        $labellist=db("search_label")->where("show_status=1")->where($whereOr)->order("update_time")->select();
        $labelstr='';
        foreach ($labellist as $label){
            $count=$this->_getLabelDataCount($label['id']);
            $bgcolor=empty($label['label_color']) ? '#009688' :$label['label_color'];
            $labelstr.='<a href="'.url('index').'?a=searchLabel&labelid='.$label['id'].'" class="layui-btn hisi-iframe" hisi-data="{width: \'100%\', height: \'100%\'}"
            style="margin-left:0px;margin-right:8px;padding:0px 15px;background-color:'.$bgcolor.'"
             title="<b>'.$label["label_name"].'【'.$count.'单】</b>">'.$label["label_name"].'<span style="color:#FFCC00">【'.$count.'单】</span></a>';
        }
        return $labelstr;
    }

    /**
     * sparkguo
     * id 串转文字
     * @param $strids 要转成文字的id串，$idkeyArr id键值对数组
     * @return string
     */
    private function _getIdstrNames($strids,$idkeyArr){
        $search_marerialStatus=[];
        $stridsArr = explode(",", $strids);
        foreach ($stridsArr as $key => $value) {
            $search_marerialStatus[]= arrayGet($idkeyArr, $value, '');
        }
        $marerialStatus_str = implode(",", $search_marerialStatus);
        return $marerialStatus_str;
    }

    /**
     * 跟据搜索标签配置搜索条件
     * date 2022.5.19  sparkguo
     * return array
     */
    private function _searchLabelWhere($labelid){
        $sql_leftjoin_order_material = "";
        $whereHaving = '1=1';
        $where_material_property = [];// 物料附加条件
        $whereRaw = ' 1=1 ';
        $where = [
            ["o.status", 'in', [0, 1]],
            ['o.client_status', '<>', 99],
            ['om.caigou_show', '>', 0]
        ];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');

        $labelinfo=db("search_label")->find($labelid);
        if(!empty($labelinfo)){
            $HistoryDate=['all'=>'','today'=>date("Y-m-d"),'yestoday'=>date("Y-m-d",strtotime("-1 day"))];
            //搜索状态时间起止
            list($start_time,$end_time)=$labelinfo['search_history']!='all' ?
                [strtotime(date($HistoryDate[$labelinfo['search_history']]." 00:00:00")),strtotime(date($HistoryDate[$labelinfo['search_history']]." ".$labelinfo['search_end_time']))] : ['',''];
            $factorIds=explode(',',$labelinfo['factory_ids']); //搜索工厂(多个
            $material_status_arr=explode(',',$labelinfo['search_data_status']); //搜索物料状态(多个
            $material_property=$labelinfo['search_materal_type']; //搜索物料类型
            $material_status_logic=$labelinfo['m_status_logic'];
        }
        if ($clientOrdernum != '') {
            $where[0] = ["1", '=', 1];//清["o.status", 'in', [0, 1]],这个条件
            $where[1] = ["1", '=', 1];
            $where[] = ['o.client_ordernum', '=', $clientOrdernum];
        }
        if ($factorIds) {
            $where[] = ['o.factory_id', 'in', $factorIds];
        }
        $where[] = ['o.caichuang_status', '=', 0];
        $where[] = ['o.chejian_status', '=', 0];

        //搜索物料类型
        switch ($labelinfo["search_materal_type"]){
            case 2://铺料
                $where[] = ['m.type', '=', "accessories"];
                $where_material_property[] = ['m.type', '=', "'accessories'"];
                break;
            case 1://面料
                $where[] = ['m.type', '<>', "accessories"];
                $where_material_property[] = ['m.type', '<>', "'accessories'"];
        }
        //$sql_leftjoin_order_material=$this->_createLeftJoinSql($labelinfo["search_materal_type"],$material_status_arr);
        $timewhere_arr=[
            1=>" o.create_time between ".$start_time." and ".$end_time //未采购 取下单时间
            ,2=>" om.caigou_start_time between ".$start_time." and ".$end_time //采购中 取开始采购时间
            ,3=>" om.tiaoshu_status_time between ".$start_time." and ".$end_time //换料中 取换料时间
            ,4=>" om.arrive_time between ".$start_time." and ".$end_time //已到料 取到料时间
            ,5=>" om.arrive_time between ".$start_time." and ".$end_time  //未批色 取到料时间
            ,6=>" om.caigou_first_time between ".$start_time." and ".$end_time //批色不通过 取批色不通时间
            ,7=>" om.caigou_over_time between ".$start_time." and ".$end_time //已批色 取批色完成时间
            ,8=>" om.caigou_over_time between ".$start_time." and ".$end_time //已批色齐套 同上
            ,9=>" om2.caigou_over_time between ".$start_time." and ".$end_time //批色未齐套 取子查询的批色完成时间
            ,10=>" om2.caigou_finish_time between ".$start_time." and ".$end_time //未购未齐套  取采购完成时间
            ,11=>" om.caigou_finish_time between ".$start_time." and ".$end_time //未购已齐套 同上
            ,12=>" om.caigou_finish_time between ".$start_time." and ".$end_time //可裁剪 同上
            ,13=>" 1=1 " //未发货 需求说及不用与其它状态关联
            ,14=>" om.send_goods_time between ".$start_time." and ".$end_time //已发货
            ,15=>" om.send_goods_time between ".$start_time." and ".$end_time //发货未齐套
            ,16=>" om.send_goods_time between ".$start_time." and ".$end_time //发货已齐套
        ];

        $oldWhere=$where; //清空where参数存新值
        $oldMaterialWhere=$where_material_property;
        $bigWhereSql=$materialBigWhereSql='';
        $searchTimeWhere=[];
        foreach($material_status_arr as $index=>$material_status) {
            $where=$where_material_property=[];
            switch ($material_status) {
                case 1://未采购
                    $where[] = ['om.is_caigou_start', '=', 0];
                    $where_material_property[] = ['om.is_caigou_start', '=', 0];
                    break;
                case 2://采购中
                    $where[] = ['om.is_caigou_start', '=', 1];
                    $where_material_property[] = ['om.is_caigou_start', '=', 1];
                    break;
                case 3://换料中
                    $where[] = ['om.tiaoshu_status', '=', 10];
                    $where_material_property[] = ['om.tiaoshu_status', '=', 10];
                    break;
                case 4://已到料 含义：按了到料，不要换料中
                    $where[] = ['om.arrive_time', '>', 0];
                    $where_material_property[] = ['om.arrive_time', '>', 0];
                    $where[] = ['om.tiaoshu_status', '<>', 10];
                    $where_material_property[] = ['om.tiaoshu_status', '<>', 10];
                    break;
                case 13://未发货
                    $where[] = ['om.send_goods_status', '=', 0];
                    $where_material_property[] = ['om.send_goods_status', '=', 0];
                    break;
                case 14://已发货
                    $where[] = ['om.send_goods_status', '=', 1];
                    $where_material_property[] = ['om.send_goods_status', '=', 1];
                    break;
                case 5://未批色
                    $where[] = ['om.caigou_status', '=', 0];
                    $where_material_property[] = ['om.caigou_status', '=', 0];
                    break;
                case 6://批色不通过
                    $where[] = ['om.caigou_status', '=', 2];
                    $where_material_property[] = ['om.caigou_status', '=', 2];
                    break;
                case 7://已批色
                    $where[] = ['om.caigou_status', '=', 1];
                    $where_material_property[] = ['om.caigou_status', '=', 1];
                    break;
                case 8://已批色齐套  不包括：已完成裁床以后的订单
                    $where[] = ['om.caigou_status', '=', 1];
                    $where[] = ['m.type', '<>', "'accessories'"];
                    $sql = "select min(om2.caigou_status) as caigou_status_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories' ";
                    $sql2 = "select max(om2.caigou_status) as caigou_status_max
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and m2.type<>'accessories' ";
                    $sql_leftjoin_order_material = " and 1=($sql) and 1=($sql2)";
                    break;
                case 9://批色未齐套
                    $where[] = ['om.caigou_status', '<>', 1];
                    //$where[] = ['m.type', '<>', "'accessories'"];
                    $sql = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' ";
                    $piSeOverTime=$labelinfo['search_history'] != 'all' ? " and ".$timewhere_arr[$material_status] : '';
                    $sql1 = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' and om2.caigou_status=1".$piSeOverTime; //已批色大于0
                    $sql_leftjoin_order_material = " and ($sql1)>0 and 1<($sql)  and ($sql)>($sql1)    ";
                    break;
                case 10://采购未齐套 有一个采购完成
                    $where[] = ['om.is_caigou_start', '<>', 2];
                    $sql = "select count(0)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $caigouOverTime=$labelinfo['search_history'] != 'all' ? " and ".$timewhere_arr[$material_status] : '';
                    $sql1 = "select max(om2.is_caigou_start) as is_caigou_start_max
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ".$caigouOverTime;
                    $sql2 = "select min(om2.is_caigou_start) as is_caigou_start_min
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql_leftjoin_order_material = " and 1<($sql)  and 2=($sql1) and 2>($sql2)  ";
                    break;
                case 11://采购已齐套 定义：只要全部物料是“采购完成”状态  或  或中有一个是“可裁剪”+其它全是“采购完成 ”
                    $whereRaw .= " and ( o.caichuang_can_do <> 1 OR o.caichuang_status <>0)";//与12 切开
                    $where[] = ['om.is_caigou_start', '=', 2];
                    $where[] = ['om.tiaoshu_status', '<>', 10];//
                    $sql = "select min(om2.is_caigou_start) as is_caigou_start_min 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql2 = "select max(om2.is_caigou_start) as is_caigou_start_max
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql3 = "select IFNULL(max(om2.tiaoshu_status), 0) 
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.tiaoshu_status=10 ";
                    $sql_leftjoin_order_material = " and 2=($sql) and 2=($sql2) and  10<>($sql3) ";
                    break;
                case 12://可裁剪 与以前的 未裁剪完成一样。
                    $where[] = ['o.caichuang_can_do', '=', 1];
                    $where[] = ['o.caichuang_status', '=', 0];
                    $sql = "select min(om2.caichuang_can_do)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  and m2.type<>'accessories' ";
                    $sql_leftjoin_order_material = " and ($sql)>0";
                    break;
                case 15://发货未齐套 //1与0的互相作用肯定物料数>=2样以上。
                    $where[] = ['om.send_goods_status', '=', 1];
                    $sql1 = "select min(om2.send_goods_status)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
//                    $sql_leftjoin_order_material = " and 1<($sql)  and 0=($sql1)  ";
                    $sql_leftjoin_order_material = " and 0=($sql1)  ";
                    break;
                case 16://发货已齐套
                    $where[] = ['om.send_goods_status', '=', 1];
                    $sql = "select min(om2.send_goods_status)
from wx_order_material om2
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0  ";
                    $sql_leftjoin_order_material = " and 1=($sql)  ";
                    break;
            }
            if($timewhere_arr[$material_status]!=" 1=1 " && !in_array($material_status,[9,10])){
                $searchTimeWhere[]=$timewhere_arr[$material_status];
            }

            //处理订单搜索条件
            $whereSql='';
            foreach ($where as $key=>$whereitem){
                $whereSql.=implode(' ',$whereitem)." and ";
            }
            $whereSql=trim($whereSql," and ");
            if($material_status_logic=='and'){ //多个物料状态搜索是并且关系
                $bigWhereSql.= " and (".$whereSql .")";
            }else{
                if(in_array($material_status,[9,10])){ //采购/批色未齐套 时，不用在未批色的结果里拼接采购/批色完成时间， 批色完成时间放到【查询有批色结果】的子查询里
                    $bigWhereSql.= " or (".$whereSql .")" ;
                }else{
                    $bigWhereSql.= $labelinfo['search_history'] != 'all' ? " or (".$whereSql ." and ".$timewhere_arr[$material_status].")" : " or (".$whereSql .")" ;//拼接时间条件
                }
            }
            //处理物料搜索逻辑
            $material_status_whereSql='';
            $where_material_property=array_merge($where_material_property,$oldMaterialWhere);
            foreach ($where_material_property as $key=>$whereitem){
                $material_status_whereSql.=implode(' ',$whereitem)." and ";
            }
            $material_status_whereSql=trim($material_status_whereSql," and ");

            if($material_status_logic=='and'){ //多个物料状态搜索是并且关系
                $materialBigWhereSql.= $material_status_whereSql != '' ? " and (".$material_status_whereSql .")" : '';
            }else{
                $materialBigWhereSql.= $material_status_whereSql != '' ? " or (".$material_status_whereSql .")" : '';
            }
        }
        if($material_status_logic=='and' && count($searchTimeWhere)>0){ //查询各状态时间点最近的记录
            $searchTimeWhereSql=implode(' or ',$searchTimeWhere);
            $bigWhereSql.= $labelinfo['search_history'] != 'all' ? " and (".$searchTimeWhereSql.")" : '';//拼接时间条件
        }
        $bigWhereSql=trim($bigWhereSql," or ");
        $materialBigWhereSql= trim($materialBigWhereSql," or ");//物料表里的或查询
        $bigWhereSql=trim($bigWhereSql," and ");
        $materialBigWhereSql= trim($materialBigWhereSql," and ");


        $materialBigWhereSql=$materialBigWhereSql!='' ? $materialBigWhereSql : [];//物料表里的或查询
        $whereRaw=$whereRaw ." and ". $bigWhereSql;
        return [
            $oldWhere,
            $whereRaw,
            $whereHaving,
            $sql_leftjoin_order_material,
            $materialBigWhereSql,
        ];
    }

    private function _createLeftJoinSql($show_materal_type,$material_status_arr){
        $big_left_join_sql=$sql_leftjoin_order_material=$where_left_join_sql='';
        switch ($show_materal_type) {
            case 0://全部
                foreach($material_status_arr as $index=>$material_status) {
                    switch ($material_status) {
                        case 1://未采购
                            $sql = "select count(0)
from wx_order_material om2 
left join wx_material m2 on (om2.material_id=m2.id)
where o.id=om2.order_id and om2.caigou_show<>0 and om2.is_caigou_start=0 ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 2://采购中
                            $sql = "select count(0)
from wx_order_material om3 
left join wx_material m3 on (om3.material_id=m3.id)
where o.id=om3.order_id and om3.caigou_show<>0 and om3.is_caigou_start=1 ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 3://换料中
                            $sql = "select count(0)
from wx_order_material om4 
left join wx_material m4 on (om4.material_id=m4.id)
where o.id=om4.order_id and om4.caigou_show<>0 and om4.tiaoshu_status=10 ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 4://已到料 含义：按了到料，不要换料中
                            $sql = "select count(0)
from wx_order_material om5 
left join wx_material m5 on (om5.material_id=m5.id)
where o.id=om5.order_id and om5.caigou_show<>0 and om5.arrive_time>0 ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                    }
                    $where_left_join_sql= !empty($sql_leftjoin_order_material) ? " or (".$sql_leftjoin_order_material .")" : '';
                }
                $big_left_join_sql.=$where_left_join_sql;
                break;
            case 1://面料
                foreach($material_status_arr as $index=>$material_status) {
                    switch ($material_status) {
                        case 1://未采购
                            $where[] = ['m.type', '<>', 'accessories'];
                            $where_material_property[] = ['m.type', '<>', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om6 
left join wx_material m6 on (om6.material_id=m6.id)
where o.id=om6.order_id and om6.caigou_show<>0 and om6.is_caigou_start=0 and m6.type<>'accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 2://采购中
                            $where[] = ['m.type', '<>', 'accessories'];
                            $where_material_property[] = ['m.type', '<>', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om7 
left join wx_material m7 on (om7.material_id=m7.id)
where o.id=om7.order_id and om7.caigou_show<>0 and om7.is_caigou_start=1 and m7.type<>'accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 3://换料中
                            $where[] = ['m.type', '<>', 'accessories'];
                            $where_material_property[] = ['m.type', '<>', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om8 
left join wx_material m8 on (om8.material_id=m8.id)
where o.id=om8.order_id and om8.caigou_show<>0 and om8.tiaoshu_status=10 and m8.type<>'accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 4://已到料 含义：按了到料，不要换料中
                            $where[] = ['m.type', '<>', 'accessories'];
                            $where_material_property[] = ['m.type', '<>', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om9 
left join wx_material m9 on (om9.material_id=m9.id)
where o.id=om9.order_id and om9.caigou_show<>0 and om9.arrive_time>0 and m9.type<>'accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 5:
                        case 6:
                        case 7:
                            $where[] = ['m.type', '<>', 'accessories'];
                            $where_material_property[] = ['m.type', '<>', 'accessories'];
                            break;
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                            break;
                    }
                    $where_left_join_sql= !empty($sql_leftjoin_order_material) ? " or (".$sql_leftjoin_order_material .")" : '';
                }
                $big_left_join_sql.=$where_left_join_sql;
                break;
            case 2://铺料
                foreach($material_status_arr as $index=>$material_status) {
                    switch ($material_status) {
                        case 1://未采购
                            $where[] = ['m.type', '=', 'accessories'];
                            $where_material_property[] = ['m.type', '=', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om10 
left join wx_material m10 on (om10.material_id=m10.id)
where o.id=om10.order_id and om10.caigou_show<>0 and om10.is_caigou_start=0 and m10.type='accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 2://采购中
                            $where[] = ['m.type', '=', 'accessories'];
                            $where_material_property[] = ['m.type', '=', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om11 
left join wx_material m11 on (om11.material_id=m11.id)
where o.id=om11.order_id and om11.caigou_show<>0 and om11.is_caigou_start=1 and m11.type='accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 3://换料中
                            $where[] = ['m.type', '=', 'accessories'];
                            $where_material_property[] = ['m.type', '=', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om12 
left join wx_material m12 on (om12.material_id=m12.id)
where o.id=om12.order_id and om12.caigou_show<>0 and om12.tiaoshu_status=10 and m12.type='accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 4://已到料 含义：按了到料，不要换料中
                            $where[] = ['m.type', '=', 'accessories'];
                            $where_material_property[] = ['m.type', '=', 'accessories'];
                            $sql = "select count(0)
from wx_order_material om13 
left join wx_material m13 on (om13.material_id=m13.id)
where o.id=om13.order_id and om13.caigou_show<>0 and om13.arrive_time>0 and m13.type='accessories' ";
                            $sql_leftjoin_order_material = "  0<($sql) ";
                            break;
                        case 5:
                        case 6:
                        case 7:
                            $where[] = ['m.type', '=', 'accessories'];
                            $where_material_property[] = ['m.type', '=', 'accessories'];
                            break;
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                            break;
                    }
                    $where_left_join_sql= !empty($sql_leftjoin_order_material) ? " or (".$sql_leftjoin_order_material .")" : '';
                }
                $big_left_join_sql.=$where_left_join_sql;
                break;
        }
        $big_left_join_sql=!empty($big_left_join_sql) ? " and ".trim($big_left_join_sql," or ") : "";
        return $big_left_join_sql;
    }

    /**
     * 设置表下面的值
     * 共 978 款   |    共 350954 件
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/9
     */
    public function otherListData()
    {
        list($where, $whereRaw, $whereHaving, $sql_leftjoin_order_material, $where_material_property) = $this->_where_index();
        //订单加一级
        order_level($where, 'o.');
        $order = "o.caigou_status asc,o.id desc";
        $list = db('order o')
            ->field("o.id,o.sku,o.quantity
")
            ->join('factory ft', "o.factory_id=ft.id", 'left')
            ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
            ->join('group g', "o.group_id=g.id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('order_size os ', 'o.id=os.order_id', 'left')
            ->join('system_user su', "o.caigou_user_id=su.id", 'left')
            ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
            ->join('material m', "om.material_id=m.id", 'left')
            ->where($where)
            ->whereRaw($whereRaw)
            ->group('o.id')
            ->having($whereHaving)
            ->select();
        $allQuantity = 0;
        $skuCount_array = [];
        foreach ($list as $k => $v) {
            $allQuantity += $v['quantity'];
            $skuCount_array[trim($v['sku'])] = 1;
        }
        $result = [
            'code' => 1,
            'msg' => '',
            'skuCount' => count($skuCount_array),
            'allQuantity' => $allQuantity,
        ];
        return json($result);
    }

    public function purchasing_index()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            //$noStat = $this->request->param('noStat/s','');
            $isAutoImport = $this->request->param('is_auto_import/d', 0);
            $stat = $this->request->param('a/s', '');
            $statCondition = $this->request->param('sc/s', '');
            $where = $detailWhere = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $factorId = $this->request->param('factory_id/d', 0);
            $orderStatus = $this->request->param('order_status/s', '');
            $clientOrdernum = $this->request->param('client_ordernum/s', '');
            $sku = $this->request->param('sku/s', '');
            $createDateRange = $this->request->param('create_date_range/s', '');
            $overDateRange = $this->request->param('over_date_range/s', '');
            $caichuangOverDateRange = $this->request->param('caichuang_over_date_range/s', '');
            $orders = $this->request->param('orders/s', '');
            $export = $this->request->param('export/d', 0);
            $detailWhere = [
                'o.factory_id' => $factorId,
                'o.order_status' => $orderStatus,
                'o.client_ordernum' => $clientOrdernum,
                'o.sku' => $sku,
                'o.create_date_range' => $createDateRange,
                'o.over_date_range' => $overDateRange,
                'o.caichuang_over_date_range' => $caichuangOverDateRange,
                'o.is_auto_import' => $isAutoImport
            ];


            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
            }
            if ($orders != '') {
                $where[] = ['o.id', 'in', $orders];
            }
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['o.ext_id', '=', $ext_id];
                    break;
            }
            if ($isAutoImport > 0) {
                $where[] = ['o.is_auto_import', '=', $isAutoImport];
            }
            //订单加一级
            order_level($where, 'o.');
            if ($factorId) {
                $where[] = ['o.factory_id', '=', $factorId];
            }
            if ($clientOrdernum == '') {
                $where[] = ['o.status', 'in', [0, 1, 2]];
                $where[] = ['o.client_status', '<>', 99];
            }
            if ($orderStatus != '') {
                switch ($orderStatus) {
                    case 1:    // 面料采购未完成（未打标）
                        $subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery})")];
                        $where[] = ['o.status', 'in', [0, 1]];
                        break;
                    case 2:    //辅料采购未完成（未打标）
                        $subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery})")];
                        $where[] = ['o.status', 'in', [0, 1]];
                        break;
                    case 3: // 换料中
                        $subQuery = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery})")];
                        $where[] = ['o.status', 'in', [0, 1, 2]];
                        break;
                    case 4: // 批色不通过
                        $subQuery = db('order_material')->where("caigou_show=1 and caigou_status=2")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery})")];
                        $where[] = ['o.status', 'in', [0, 1, 2]];
                        break;
                    case 5: // 面料已到料
                        $subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type != 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery})")];
                        $where[] = ['o.status', 'in', [0, 1]];
                        break;
                    case 6: // 已批色
                        $subQuery11 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery22 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery33 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery11})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery22})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery33})")];

//    					$subQuery = db('order_material')->where("caigou_show=1 and caigou_over_time <> 0")->distinct(true)->field('order_id')->buildSql();
//    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];						//dump($subQuery);
                        $where[] = ['o.status', 'in', [0, 1, 2]];
                        break;
                }
                $where[] = ['o.stock_type', 'not in', '10,11'];
            }

            if ($clientOrdernum != '') {
                $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
            }
            if ($sku != '') {
                $where[] = ['o.sku', 'like', "%" . $sku . "%"];
            }
            if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
            }
            if ($overDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
                $where[] = ['o.over_time', 'between', [$startTime, $endTime + 86399]];
            }
            if ($caichuangOverDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
                $where[] = ['o.caichuang_over_time', 'between', [$startTime, $endTime + 86399]];
            }
            if ($statCondition != "") {
                switch ($statCondition) {
                    case "allCount":    // 全部
                        break;
                    case "fabricCgOverCount":    //面料采购已完成单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        break;
                    case "returnMaterialCount":    //退料中
                        $subQuery1 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];
                        break;
                    case "fabricCgNotCount": // 面料采购未完成单
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        break;
                    case "apColorOverCount": // 已批色单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                        break;
                    case "apColorNotCount": // 未批色单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery2})")];

                        break;
                    case "apColorNoCount": // 批色不通过单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                        $subQuery4 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=2")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery4})")];

                        break;
                    case "ckClothSkOverCount": // 已验布缩水的单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $subQuery2 = db('order_material_item omi')->join('order_material om', "omi.order_material_id=om.mid", 'left')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and omi.is_return=0 and om.caigou_show=1 and ((om.need_checkcloth=1 and omi.is_checkcloth=0) or (om.need_shrink=1 and omi.is_shrink=0))")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                        break;
                    case "ckClothSkNotCount": //未验布缩水的单数=面料采购已完成单-已验布缩水的单数
                        $subQuery1 = db('order_material_item omi')->join('order_material om', "omi.order_material_id=om.mid", 'left')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and omi.is_return=0 and om.caigou_show=1 and ((om.need_checkcloth=1 and omi.is_checkcloth=0) or (om.need_shrink=1 and omi.is_shrink=0))")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];

                        break;
                    case "caichuangOverCount": // 已裁床单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                        $where[] = ['o.caichuang_over_time', '<>', 0];

                        break;
                    case "caichuangNotCount": ////未裁床单数=批色完成-已裁床单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $subQuery3 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=2")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery4})")];
                        $where[] = ['o.caichuang_over_time', '=', 0];
                        break;
                    case "acOverCount": // 辅料发放单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery4})")];
                        $where[] = ['o.caichuang_over_time', '<>', 0];
                        $subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery3})")];
                        break;
                    case "acNotCount": // 辅料未发放单数
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
                        $subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery1})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery2})")];
                        $where[] = ['o.id', 'exp', Db::raw("not in({$subQuery4})")];
                        $where[] = ['o.caichuang_over_time', '<>', 0];
                        $subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery3})")];
                        break;
                    case "acNoCount": //辅料采购未完成
                        $subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_caigou_start!=2")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['o.id', 'exp', Db::raw("in({$subQuery1})")];
                        $where[] = ['o.status', 'in', [0, 1]];
                        break;
                }
                $where[] = ['o.stock_type', 'not in', '10,11'];
            }
            $purchasingService = new PurchasingService();

            $data['code'] = 0;
            $data['msg'] = '';
            // 订单进度统计
            if ($page == 1 && $stat == "") {
                $data['stat'] = $purchasingService->getPurchasingStatV2(FACTORY_IDS, $where, $detailWhere);
            }
            return json($data);
        }
    }

    private function getMaterialStatusV2($omInfo)
    {
        $result = [
            'is_make_tag' => $omInfo['is_make_tag'],//是否打标
            'is_caigou_start' => $omInfo['is_caigou_start'],    // 采购状态（0未开始，1采购中，2采购完成）
            'is_checkcloth' => $omInfo['need_checkcloth'],    // 验布状态（0无需验布，1验布未完成，2验布完成）
            'is_shrink' => $omInfo['need_shrink'],    // 缩水状态（0无需缩水，1缩水未完成，2缩水完成）
            'material_return' => 0, // 换料状态（0无换料，1换料中，2换料完成）
            'caigou_arrive_status' => $omInfo['is_caigou_start'],    // 采购状态与到料操作 合成（0未开始，1采购中，2采购完成 10已到料 20不显示内容）
        ];

        // 检测是否验布完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_checkcloth'] == 1 && $omInfo['cloth_0'] == $omInfo['tiaoshu']) {
            $result['is_checkcloth'] = 2;
        }
        // 检测是否缩水完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_shrink'] == 1 && $omInfo['cloth_1'] == $omInfo['tiaoshu']) {
            $result['is_shrink'] = 2;
        }
        // 换料状态
//        if ($omInfo['material_return_0'] > 0) {
//            $result['material_return'] = 1;
//        } elseif ($omInfo['material_return_1'] > 0) {
//            $result['material_return'] = 2;
//        } elseif ($omInfo['material_return_2'] > 0) {
//            $result['material_return'] = 1;
//        }
        //采购状态与到料操作 合成
        if ($omInfo['arrive_time_first'] > 0 && $result['caigou_arrive_status'] <= 1) {
            $result['caigou_arrive_status'] = 10;
        }
        if ($omInfo['tiaoshu_status'] == 10) {
            $result['caigou_arrive_status'] = 20;
        }
        return $result;
    }

    private function _deal_order_size_list($order_size_list)
    {
        if (trim($order_size_list) == '') {
            return [];
        }
        $res = [];
        $list = explode(';', $order_size_list);
        foreach ($list as $k => $v) {
            $temp = explode(',', $v);
            $res[] = [
                'size_name' => $temp[1],
                'order_count' => $temp[2],
                'shicai_count' => $temp[3],
                'jiaohuo_count' => $temp[4],
                'jiaohuo_tail_count' => $temp[5],
                'delivery_count' => $temp[6],
                'daohuo_count' => $temp[7],
            ];
        }
        return $res;
    }

    /**
     * 保存采购备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function remark()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $remark = $this->request->param('remark/s', '');
        $upData = [
            'caigou_remark' => $remark,
            'update_time' => time(),
        ];
        $ret = db('order')->where('id', $orderId)->update($upData);
        $this->addOrderLog($orderId, '', "保存采购备注[{$remark}]");
        if ($ret) {
            return $this->Json(1, '保存备注信息成功');
        } else return $this->Json(0);
    }

    public function updateCaichuangCanDo()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $orderMaterialService = new OrderMaterialService();
        //更新裁剪状态
        $orderMaterialService->updateCaichuangStatusV2($orderId, 0);
        return $this->Json(1);
    }

    /**
     * 到料
     *
     * @date 2020年12月11日
     *
     */
    public function arriveTime()
    {
        $mid = $this->request->param('mid/d', 0);
        if ($mid == 0) return $this->Json(0);
        $orderMaterialService = new OrderMaterialService();
        try {
            db()->startTrans();
            $data = $orderMaterialService->arriveTime($this, $mid);
            $orderId = db('order_material')->where('mid', $mid)->value('order_id', 0);
            // 设置裁床基准物料（客户用量最大的物料）
            $orderMaterialService = new OrderMaterialService();
            $orderMaterialService->setCaichuangStandard($data['info']['order_id']);
            db()->commit();
            return $this->Json(1);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 发货标识  0未发货1已发货 与订单发货信息无关
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/21
     */
    public function send_goods()
    {
        $mid = $this->request->param('mid/d', 0);
        $info = db('order_material om')
            ->field("om.mid,om.material_id,om.order_id,om.client_ordernum,om.send_goods_status
                ,om.tiaoshu,om.caigou_status,om.factory_id
                ,m.name,m.type,m.color")
            ->join('material m', "om.material_id=m.id", 'left')
            ->where('om.mid', $mid)
            ->find();
        if (!isset($info['send_goods_status']) || $info['send_goods_status'] == 1) {
            return $this->Json(0, '操作失败，已发货');
        }
        db()->startTrans();
        try {
            $result = db('order_material')->where('mid', $mid)->update([
                'send_goods_status' => 1,
                'send_goods_time' => time(),
            ]);
            // 记录操作日志
            $logData = [
                'order_material_id' => $mid,
                'factory_id' => $info['factory_id'],
                'material_id' => $info['material_id'],
                'material_name' => $info['name'],
                'material_type' => $info['type'],
                'type' => 3,
                'order_id' => $info['order_id'],
                'client_ordernum' => $info['client_ordernum'],
                'color' => $info['color'],
                'tiaoshu' => $info['tiaoshu'],
                'remark' => '',
                'stalls_id' => 0,
                'is_from_stock' => 0,
                'is_renew' => 0,
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time(),
            ];
            db('order_material_log')->insertGetId($logData);
            db()->commit();
            return $this->Json(1);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 打标
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function makeTag()
    {
        $mid = $this->request->param('mid/d', 0);
        $stallsId = $this->request->param('stalls_id/d', 0);
        $number = $this->request->param('number/d', 0);
        $isFromStock = $this->request->param('is_from_stock/d', 0);//是否来自库存（0否，1是）
        $isShare = $this->request->param('is_share/d', 0);//是否共用（0否，1是）
        $isRenew = $this->request->param('is_renew/d', 0);//是否换料
        $remark = $this->request->param('remark/s', '');
        $clothNums = $this->request->param('cloth_nums/s', '');

        $orderService = new OrderService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();

        $orderMaterialInfo = $orderMaterialService->getInfoById($mid);
        $materialInfo = arrayGet($orderMaterialInfo, 'mInfo', []);
        $orderInfo = $orderService->getInfoById(arrayGet($orderMaterialInfo, 'order_id', 0));

        if (empty($orderMaterialInfo) || empty($orderInfo)) {
            return $this->error('数据异常');
        }

        if ($this->request->isAjax()) {

            if ($number < 1) {
                return $this->error("条数录入错误，仅允许输入正整数");
            }

            try {
                db()->startTrans();

                $needShrink = $orderMaterialInfo['need_shrink'];

                $oud = [];
                $oud['shiji_caigou_count'] = $orderMaterialInfo['shiji_caigou_count'] + $number;
                if ($orderMaterialInfo['tiaoshu_detail'] == '' && $number > 0) {
                    $oud['tiaoshu_detail'] = abs($number);
                } else {
                    $oud['tiaoshu_detail'] = $orderMaterialInfo['tiaoshu_detail'] . ($number < 0 ? $number : '+' . $number);
                }
                $oud['tiaoshu'] = $oud['shiji_caigou_count'];
                $orderMaterialInfo['tiaoshu_status'] == 10 && $oud['tiaoshu'] > 0 && $oud['tiaoshu_status'] = 11;
                $oud['tiaoshu_status_time'] = time();
                $oud['is_make_tag'] = 1;
                $oud['make_tag_time'] = time();
                $oud['make_tag_time_first'] = $orderMaterialInfo['make_tag_time_first'] > 0 ? $orderMaterialInfo['make_tag_time_first'] : time();
                $oud['is_caigou_start'] = 2;
                $oud['caigou_finish_time'] = time();//采购完成时间
                $oud['is_share'] = $isShare;
                $oud['caigou_confirm_status'] = 1;
                $oud['caigou_confirm_time'] = time();
                $oud['update_time'] = time();


                // 处理兴国工厂布料不需要缩水
                $excludeIds = trim(config('mp.shrink_task_exclude_factory_id'));
                if (in_array($orderInfo['factory_id'], explode(',', $excludeIds))) {
                    $oud['need_shrink'] = $needShrink = 0;
                }

                $res = db('order_material')->where('mid', $mid)->update($oud);
                //到料按钮自动按下
                $data = $orderMaterialService->arriveTime($this, $mid);
                // 判断本次是否是换料（即退换料进度表里是否有 换料中状态）
                $isRenew = 0;    // 是否换料
                $where = [
                    'order_id' => $orderMaterialInfo['order_id'],
                    'material_id' => $orderMaterialInfo['material_id'],
                    'status' => 1,
                ];
                $mrList = db('material_return')->where($where)->select();
                if ($mrList) {
                    $isRenew = 1;
                    // 将原有换料进行中的记录变更为 审核中
                    $upData = [
                        'status' => 2,
                        'update_time' => time()
                    ];
                    foreach ($mrList as $k => $v) {
                        if ($v['is_reduce'] == 0 && $v['type'] == 1) {
                            $upData['is_reduce'] = 1;

                            // 条数减扣
                            if ($v['order_material_id'] > 0) {
                                $omInfo = $orderMaterialService->getInfoById($v['order_material_id'], 'mid,tiaoshu,tiaoshu_detail');
                                if ($omInfo && $omInfo['tiaoshu'] > 0) {
                                    $orderMaterialService->material_return_update($mid);
                                }
                            }
                        }
                        db('material_return')->where('id', $v['id'])->update($upData);
                    }
                }

                // 记录操作日志
                $logData = [
                    'order_material_id' => $mid,
                    'factory_id' => $orderMaterialInfo['factory_id'],
                    'material_id' => arrayGet($materialInfo, 'id', 0),
                    'material_name' => arrayGet($materialInfo, 'name', ''),
                    'material_type' => arrayGet($materialInfo, 'type', ''),
                    'type' => 1,
                    'order_id' => $orderMaterialInfo['order_id'],
                    'client_ordernum' => $orderInfo['client_ordernum'],
                    'color' => arrayGet($materialInfo, 'color', ''),
                    'tiaoshu' => $number,
                    'remark' => $remark,
                    'stalls_id' => $stallsId,
                    'is_from_stock' => $isFromStock,
                    'is_renew' => $isRenew,
                    'admin_id' => ADMIN_ID,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                db('order_material_log')->insertGetId($logData);

                // 获取最大的布号
                $clothNum = $orderMaterialItemService->getMaxClothNum($orderMaterialInfo['order_id'], $orderMaterialInfo['material_id']);

                $clothNumArr = [];
                if ($number > 0) {
                    for ($n = 1; $n <= $number; $n++) {
                        // 插入材料条数记录表
                        $itemData = [
                            'order_material_id' => $mid,
                            'material_id' => $orderMaterialInfo['material_id'],
                            'order_id' => $orderMaterialInfo['order_id'],
                            'client_ordernum' => $orderInfo['client_ordernum'],
                            'stalls_id' => $stallsId,
                            'cloth_num_full' => $oud['shiji_caigou_count'] . '-' . ($clothNum + $n),
                            'cloth_num' => $clothNum + $n,
                            'is_renew' => $isRenew,
                            'is_from_stock' => $isFromStock,
                            'need_checkcloth' => $orderMaterialInfo['need_checkcloth'],
                            'need_shrink' => $needShrink,
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                        db('order_material_item')->insertGetId($itemData);
                        $clothNumArr[] = $itemData['cloth_num'];
                    }
                }
                $this->addOrderLog($orderMaterialInfo['order_id'], $orderInfo['client_ordernum'], "物料[" . getMaterialName(arrayGet($materialInfo, 'id', 0)) . "（mid {$orderMaterialInfo['mid']}）]打标{$number}条");
//                db()->commit();

                $returnData = [
                    "mid" => $mid,
                    "shiji_caigou_count" => $oud['shiji_caigou_count'],
                    "tiaoshu_detail" => $oud['tiaoshu_detail'],
                    "tiaoshu" => $oud['tiaoshu_detail'],
                    "url" => url('makeTag', ['mid' => $mid, 'number' => $oud['shiji_caigou_count'], 'is_from_stock' => $isFromStock, 'is_renew' => $isRenew, 'cloth_nums' => implode('-', $clothNumArr)]),
                ];
                //更新裁剪状态
                $orderMaterialService->updateCaichuangStatusV2($orderMaterialInfo['order_id'], $mid, $this);
                //更新采购状态
                $orderMaterialService->update_caigou_status([], 0, [$orderMaterialInfo['order_id']]);
                db()->commit();
                return $this->Json(1, "保存订单（ID{$orderMaterialInfo['order_id']}，MID{$mid}）条数成功", $returnData);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, "打标失败，" . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }

        $clothNumMap = db('order_material_item')->where('order_material_id', $mid)->where('cloth_num', 'in', explode('-', $clothNums))->order('cloth_num asc')->column('id,cloth_num_full,cloth_num');

        foreach ($clothNumMap as $k => &$v) {
            $msg = "A{$v['id']}-{$v['cloth_num_full']}";
            $qrCode = new QrCode($msg);
            $v['qrcode'] = $qrCode->writeDataUri();
        }

        $assign = [
            'materialInfo' => $materialInfo,
            'orderInfo' => $orderInfo,
            'factoryKV' => [0 => ''] + getFactoryKV(true),
            'materialType' => config('mimo.material_type'),
            'number' => $number,
            'isFromStock' => $isFromStock,
            'isRenew' => $isRenew,
            'clothNums' => $clothNumMap
        ];
        $this->view->engine->layout('system@layout_empty');
        return $this->assign($assign)->fetch();
    }

    /**
     * 清除打标信息 重新打标
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/13
     */
    public function delMakeTag()
    {
        $mid = $this->request->param('mid/d', 0);
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialInfo = $omInfo = $orderMaterialService->get_order_material_list([], [$mid])[0];
        $where = [
            'order_id' => $orderMaterialInfo['order_id'],
            'material_id' => $orderMaterialInfo['material_id'],
        ];
        $mrList_count = db('material_return')->where($where)->count();
        if ($mrList_count > 0) {
            return $this->Json(0, "退换料进度已有申请，不能删除");
        }
        //这里也要修复下，如退料的就不算
        $sh_count = db('checkcloth_shrink')->where(['order_id' => $orderMaterialInfo['order_id'],])->count();
        if ($sh_count > 0) {
            return $this->Json(0, "验布或缩水已有记录，不能删除");
        }
        try {
            db()->startTrans();
            db('order_material_item')->where([
                ['order_id', '=', $orderMaterialInfo['order_id']],
                ['order_material_id', '=', $mid],
            ])->delete();

            $oud = [];
            $oud['shiji_caigou_count'] = 0;
            $oud['tiaoshu_detail'] = '';
            $oud['tiaoshu'] = $oud['shiji_caigou_count'];
            $oud['tiaoshu_status'] = 0;
            $oud['tiaoshu_status_time'] = 0;
            $oud['is_make_tag'] = 0;
            $oud['make_tag_time'] = 0;
            $oud['make_tag_time_first'] = 0;
            $oud['is_caigou_start'] = 1;
            $oud['caigou_finish_time'] = 0;//采购完成时间
//        $oud['is_share'] = $isShare;
//        $oud['caigou_confirm_status'] = 1;
//        $oud['caigou_confirm_time'] = time();
//        $oud['update_time'] = time();
//        // 处理兴国工厂布料不需要缩水
//        $excludeIds = trim(config('mp.shrink_task_exclude_factory_id'));
//        if (in_array($orderInfo['factory_id'], explode(',', $excludeIds))) {
//            $oud['need_shrink'] = $needShrink = 0;
//        }

            $res = db('order_material')->where('mid', $orderMaterialInfo['mid'])->update($oud);

            // 记录操作日志
            $logData = [
                'order_material_id' => $mid,
                'factory_id' => $omInfo['factory_id'],
                'material_id' => $omInfo['material_id'],
                'material_name' => $omInfo['name'],
                'material_type' => $omInfo['type'],
                'type' => 2,
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'color' => $omInfo['color'],
                'tiaoshu' => $omInfo['tiaoshu'],
                'remark' => '删除所有布条',
                'stalls_id' => 0,
                'is_from_stock' => 0,
                'is_renew' => 0,
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time(),
            ];
            db('order_material_log')->insertGetId($logData);

            db()->commit();
            return $this->Json(1, "删除成功");
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "删除失败，" . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    public function delClothnumV2()
    {
        $mid = $this->request->param('mid/d', 0);
        $id = $this->request->param('id/d', 0);
        $orderMaterialService = new OrderMaterialService();
        $omInfo = $orderMaterialService->get_order_material_list([], [$mid])[0];
        $clothInfo = db('order_material_item')->where(['id' => $id,])->find();
        //此布号在 material_return表 或checkcloth_shrink表里有数据就不能删除了。
        $mrList_count = db('material_return')->where([
            'order_id' => $omInfo['order_id'],
            'material_id' => $omInfo['material_id'],
            'cloth_num' => $clothInfo['cloth_num'],
        ])->count();
        if ($mrList_count > 0) {
            return $this->Json(0, "退换料进度已有申请，不能删除");
        }
        $sh_count = db('checkcloth_shrink')->where([
            'order_id' => $omInfo['order_id'],
            'material_id' => $omInfo['material_id'],
            'cloth_num' => $clothInfo['cloth_num'],
        ])->count();
        if ($sh_count > 0) {
            return $this->Json(0, "验布或缩水已有记录，不能删除");
        }
        try {
            db()->startTrans();
            $temp = db('order_material_item')->where([
                'id' => $id,
                'flag_del' => 0,
            ])->update([
                'flag_del' => 1,
                'update_time' => time(),
            ]);
            if ($temp != 1) {
                db()->rollback();
                return $this->Json(0, "删除失败flag_del");
            }
            $orderMaterialService->material_return_update($mid);
            // 记录操作日志
            $logData = [
                'order_material_id' => $mid,
                'factory_id' => $omInfo['factory_id'],
                'material_id' => $omInfo['material_id'],
                'material_name' => $omInfo['name'],
                'material_type' => $omInfo['type'],
                'type' => 2,
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'color' => $omInfo['color'],
                'tiaoshu' => 1,
                'cloth_num' => $clothInfo['cloth_num'],
                'remark' => "删除布条{$omInfo['tiaoshu']}-{$clothInfo['cloth_num']}",
                'stalls_id' => 0,
                'is_from_stock' => 0,
                'is_renew' => 0,
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time(),
            ];
            db('order_material_log')->insertGetId($logData);
            // 记录操作日志
            $this->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "删除物料[{$omInfo['name']}]布条{$omInfo['tiaoshu']}-{$clothInfo['cloth_num']}");
            db()->commit();
            return $this->Json(1, "删除成功");
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "删除失败，" . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }


    /**
     * 批色
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function approvalColor()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $mid = $this->request->param('mid/d', 0);
        $status = $this->request->param('status/d', 1);

        $orderService = new OrderService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $orderInfo = $orderService->getInfoById($orderId);

        if (empty($orderInfo)) return $this->error('订单不存在');

        try {
            db()->startTrans();
            if ($mid > 0) {//单个物料批色
                $order_update = $orderMaterialService->update_caigou_status([$mid], $status);
                //到料按钮自动按下
                $data = $orderMaterialService->arriveTime($this, $mid);
            } else {//全部批色
                $list = db('order_material om')
                    ->field("om.mid,om.order_id,om.tiaoshu,om.caigou_first_time")
                    ->join('material m', "om.material_id=m.id", 'left')
                    ->where([
                        ['om.order_id', '=', $orderId],
                        ['om.material_id', '>', 0],
                        ['om.caigou_show', '<>', 0],// 去除不在采购进度显示条目
                        ['m.type', '<>', 'accessories'],
                    ])->select();
                foreach ($list as $k => $v) {
                    $orderMaterialService->update_caigou_status([$v['mid']], 1);
                    //到料按钮自动按下
                    $data = $orderMaterialService->arriveTime($this, $v['mid']);
                }
                $order_update = $orderMaterialService->update_caigou_status([], 0, [$orderId]);
            }
            $orderMaterialService->updateCaichuangStatusV2($orderId, 0, $this);//更新裁剪状态
            if ($orderMaterialService->checkCaichangCanDoStatus($orderId)) {
                // 设置裁床基准物料（客户用量最大的物料）
                $orderMaterialService->setCaichuangStandard($orderId);
            }
            if ($mid == 0) {
                $this->addOrderLog($orderId, $orderInfo['client_ordernum'], "全部批色通过");
            } elseif ($mid > 0) {
                $omInfo = $orderMaterialService->getInfoById($mid);
                $this->addOrderLog($orderId, $orderInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]批色（mid {$mid}）" . ($status == 1 ? '通过' : '不通过'));
            }
            db()->commit();
            return $this->Json(1, '', ['is_all_over' => $orderId > 0 ? 1 : 0, 'order_id' => $orderId]);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 退料
     *
     * @author KING
     * @date 2020年5月12日
     *
     */
    public function returnClothnum()
    {
        $stallsKV = getStallsKV();
        $mid = $this->request->param('mid/d', 0);
        $from = $this->request->param('from/s', '');    // caichuang从裁床发起退料
        $materialService = new MaterialService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $omInfo = $orderMaterialService->getInfoById($mid);

        if ($this->request->isAjax()) {
            $model = $this->request->param('model/s', 'get_list');
            if ($model == 'get_list') {
                $omList = db('order_material_item')->where(["order_material_id" => $mid, 'flag_del' => 0,])->select();
                foreach ($omList as $k => $v) {
                    $omList[$k]['mInfo'] = $materialService->getInfoById($v['material_id']);
                    $omList[$k]['stalls_name'] = arrayGet($stallsKV, 'stalls_id', '');
                    $omList[$k]['fabric_width'] = arrayGet($omInfo, 'fabric_width', '');
                    $omList[$k]['weight'] = arrayGet($omInfo, 'weight', '');
                }
                $data['data'] = $omList;
                $data['count'] = count($omList);
                $data['code'] = 0;
                $data['msg'] = '';
                return json($data);
            }

            // 整条退料
            if ($model == 'return_clothnum') {
                $id = $this->request->param('id/d', 0);
                $reasonArr = $this->request->param('reason/a', []);

                try {
                    db()->startTrans();

                    $info = $orderMaterialItemService->getInfoById($id);

                    if (!$info) {
                        return $this->Json(0, "未找到相应数据");
                    }

                    if ($info['is_return'] > 0) {
                        return $this->Json(0, "该布号已退料");
                    }

                    // 标记退料
                    $omiData = [
                        'is_return' => 1,
                        'update_time' => time()
                    ];
                    db('order_material_item')->where('id', $id)->update($omiData);

                    // 扣除条数
                    if ($omInfo && $omInfo['tiaoshu'] > 0) {
                        // 同步到退料进度表里

                        $mrData = [
                            'material_id' => $info['material_id'],
                            'order_id' => $info['order_id'],
                            'client_ordernum' => $info['client_ordernum'],
                            'order_material_id' => $info['order_material_id'],
                            'order_material_item_id' => $info['id'],
                            'cloth_num' => $info['cloth_num'],
                            'type' => 1,
                            'reason' => implode(',', $reasonArr),
                            'admin_id' => ADMIN_ID,
                            'is_reduce' => 0,
                            'status' => 0,
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                        $materialReturnId = db('material_return')->insertGetId($mrData);

                        // 记录退料操作日志
                        (new MaterialReturnService())->addLog($materialReturnId, 1);
                    }

                    // 重新计算唛架信息
                    if ($from == 'caichuang') {
                        $orderMaterialService->resetWheatData($mid);
                    }
                    $orderMaterialService->updateCaichuangStatusV2($info['order_id'], $info['order_material_id'], $this);
                    $this->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "物料[" . getMaterialName($omInfo['material_id']) . "]整条退料");
                    db()->commit();
                    return $this->Json(1);
                } catch (\Exception $e) {
                    db()->rollback();
                    return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
                }
            }

            // 按米退料
            if ($model == 'return_length') {
                $id = $this->request->param('id/d', 0);
                $returnLength = $this->request->param('length/d', 0);
                $reasonArr = $this->request->param('reason/a', []);

                try {
                    db()->startTrans();
                    $info = $orderMaterialItemService->getInfoById($id);

                    if (!$info) {
                        return $this->Json(0, "未找到相应数据");
                    }

                    if ($info['is_return'] > 0) {
                        return $this->Json(0, "该布号已退料");
                    }
                    $upData = [
                        'return_length' => $returnLength,
                        'update_time' => time(),
                    ];
                    db('order_material')->where('mid', $mid)->update($upData);

                    // 同步到退料进度表里
                    $mrInfo = db('material_return')->where('type', 2)->where('order_material_id', $mid)->field('id')->findOrEmpty();
                    $mrData = [
                        'material_id' => $omInfo['material_id'],
                        'order_id' => $omInfo['order_id'],
                        'client_ordernum' => $omInfo['client_ordernum'],
                        'order_material_id' => $mid,
                        'order_material_item_id' => $info['id'],
                        'return_length' => $returnLength,
                        'type' => 2,
                        'reason' => implode(',', $reasonArr),
                        'admin_id' => ADMIN_ID,
                        'update_time' => time(),
                    ];
                    if ($mrInfo) {
                        db('material_return')->where('id', $mrInfo['id'])->update($mrData);
                    } else {
                        $mrData['status'] = 0;
                        $mrData['create_time'] = time();
                        db('material_return')->insertGetId($mrData);
                    }

                    // 重新计算唛架信息
                    if ($from == 'caichuang') {
                        $orderMaterialService->resetWheatData($mid);
                    }
                    $orderMaterialService->updateCaichuangStatusV2($info['order_id'], $info['order_material_id'], $this);
                    $this->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "物料[" . getMaterialName($omInfo['material_id']) . "]按米退料{$returnLength}米");
                    db()->commit();
                    return $this->Json(1);
                } catch (\Exception $e) {
                    db()->rollback();
                    return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
                }
            }
        }

        $assign = [
            'mid' => $mid,
            'from' => $from,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 删除布条
     *
     * @author KING
     * @date 2020年5月12日
     *
     */
    private function delClothnum()
    {
        $stallsKV = getStallsKV();
        $mid = $this->request->param('mid/d', 0);
        $id = $this->request->param('id/d', 0);

        $materialService = new MaterialService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $omInfo = $orderMaterialService->getInfoById($mid);
        $omiInfo = $orderMaterialItemService->getInfoById($id);
        if (empty($omInfo) || empty($omiInfo)) return $this->error('请求异常');
        if (db('checkcloth_shrink')->where('order_material_item_id', $id)->find()) {
            return $this->error('已存在验布或缩水记录，不允许删除');
        }

        try {
            db()->startTrans();

            db('order_material_item')->where("id", $id)->delete();

            // 记录操作日志
            $logData = [
                'order_material_id' => $mid,
                'factory_id' => $omInfo['factory_id'],
                'material_id' => arrayGet($omInfo, 'material_id', 0),
                'material_name' => arrayGet($omInfo['mInfo'], 'name', ''),
                'material_type' => arrayGet($omInfo['mInfo'], 'type', ''),
                'type' => 2,
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'color' => arrayGet($omInfo['mInfo'], 'color', ''),
                'tiaoshu' => 1,
                'remark' => '删除布条' . $omiInfo['cloth_num_full'],
                'stalls_id' => 0,
                'is_from_stock' => 0,
                'is_renew' => 0,
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time(),
            ];
            db('order_material_log')->insertGetId($logData);

            $orderMaterialService->material_return_update($mid);
            $tiaoshu = db('order_material')->where("mid", $mid)->value('tiaoshu');
            if ($tiaoshu == 0) {
                db('order_material')->where("mid", $mid)->update(['is_make_tag' => 0]);
            }

            // 记录操作日志
            $this->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "删除物料[{$omInfo['mInfo']['name']}]布条" . $omiInfo['cloth_num_full']);

            db()->commit();

            return $this->Json(1, "操作成功");
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，" . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 获取物料状态
     *
     * @author King
     * @date 2020年10月13日
     *
     */
    public function getMaterialStatus()
    {
        $mid = $this->request->param('mid/d', 0);
        $orderMaterialService = new OrderMaterialService();
        $stockService = new StockService();
        $stockLogService = new StockLogService();
        $materialStockUseService = new MaterialStockUseService();
        $materialStockService = new MaterialStockService();

        $omInfo = $orderMaterialService->getInfoById($mid);

        $omInfo['total_material_dosage'] = round(1 * $omInfo['material_dosage'], 2);

        // 余料使用
        if (arrayGet($omInfo['mInfo'], 'type') == 'accessories') {
            $omInfo['stock_use_num'] = $stockLogService->getUseNum($omInfo['material_id'], $omInfo['order_id']);
        } else {
            $applyAndUsed = $materialStockUseService->getApplyAndUsed($omInfo['material_id'], $omInfo['order_id']);
            $metreLeftInfo = $materialStockService->checkMetreLeft($omInfo['material_id']);
            $omInfo['check_metre_left'] = $metreLeftInfo;
            $omInfo['apply_and_used'] = $applyAndUsed;
        }

        // 采购状态
        if (arrayGet($omInfo['mInfo'], 'type') == 'accessories') {
        } else {
            $omInfo['metre_left'] = $materialStockService->getMetreLeft($omInfo['material_id']);
        }

        $omInfo['material_status'] = $orderMaterialService->getMaterialStatus($mid);
        return $this->Json(1, '', $omInfo);
    }

    /**
     * 导出xls
     *
     * @param string $fileName
     * @param array $data
     * @author KING date 2020年08月11日
     *
     */
    private function _exportXls($fileName, $data, $stat)
    {
        $head = ['客户订单号', 'SKU', '图片', '总数', '采购执行人', '材料名称', '材料SKU', '供应商', '型号', '单件用量', '批色时间', '采购量', '采购单位', '单价', '实际采购量', '条数'];

        $phpExcel = getExcelObj();
        $sheet = $phpExcel->setActiveSheetIndex(0);
        $objDate = new \PHPExcel_Shared_Date();
        $objFormat = new \PHPExcel_Style_NumberFormat();
        // 表头处理
        foreach ($head as $k => $v) {
            $cellKey = getExcelLetter($k);
            $sheet->getColumnDimension($cellKey)->setWidth(20);
            $sheet->setCellValue($cellKey . "1", $v);
            $sheet->getRowDimension(1)->setRowHeight(30);
            $sheet->getStyle($cellKey . "1")->getFont()->setBold(true);
            $sheet->getStyle($cellKey . "1")->getAlignment()->setVertical('center');
            $sheet->getStyle($cellKey . "1")->getFont()->getColor()->setARGB("FF0000FF");
        }

        $skuService = new SkuService();
        require_once env('root_path') . 'plugins/excel/phpexcel/Classes/PHPExcel/Worksheet/Drawing.php';

        $row = 2; // 当前行
        $n = 0;
        foreach ($data as $k => $v) {
            if (count($v['omList']) > 1) {
                $endCol = $row + count($v['omList']) - 1;
                $sheet->mergeCells('A' . $row . ':A' . $endCol);
                $sheet->mergeCells('B' . $row . ':B' . $endCol);
                $sheet->mergeCells('C' . $row . ':C' . $endCol);
                $sheet->mergeCells('D' . $row . ':D' . $endCol);
                $sheet->mergeCells('E' . $row . ':E' . $endCol);
            }

            $sheet->getStyle('A' . $row)->getAlignment()->setVertical('center');
            $sheet->getStyle('B' . $row)->getAlignment()->setVertical('center');
            $sheet->getStyle('C' . $row)->getAlignment()->setVertical('center');
            $sheet->getStyle('D' . $row)->getAlignment()->setVertical('center');
            $sheet->getStyle('E' . $row)->getAlignment()->setVertical('center');

            $sheet->setCellValueExplicit('A' . $row, $v['client_ordernum'], 'n');
            $sheet->setCellValueExplicit('B' . $row, $v['sku'], 's');

            // 图片
            $cellVal = $skuService->getPicBySku($v['sku'], false);
            if ($cellVal && env('env') == 'production' && stripos($cellVal, IMG_URL) !== false && $stat == "") {
               /* $sheet->getRowDimension($row)->setRowHeight(100);
                $cellVal = env('root_path') . 'public/' . str_replace(IMG_URL, "", $cellVal);
                if (file_exists($cellVal)) {
                    $objDrawing = new \PHPExcel_Worksheet_Drawing();
                    // 设置图片路径 切记：只能是本地图片
                    $objDrawing->setPath($cellVal);
                    // 设置图片高度
                    $objDrawing->setWidth(100);
                    // $objDrawing->setHeight(80);
                    // 设置图片要插入的单元格
                    $objDrawing->setCoordinates('C' . $row);
                    // 设置图片所在单元格的格式
                    $objDrawing->setOffsetX(0);
                    $objDrawing->setRotation(0);
                    $objDrawing->getShadow()->setVisible(false);
                    $objDrawing->setWorksheet($sheet);
                }*/
            } else {
                $sheet->setCellValueExplicit('C' . $row, '', 's');
            }

            // 总数
            $sheet->setCellValueExplicit('D' . $row, "总数：" . $v['quantity'], 'n');
            $sheet->getStyle('D' . $row)->getAlignment()->setWrapText(TRUE);
            $sheet->setCellValueExplicit('E' . $row, $v['caigou_user_name'], 's');

            foreach ($v['omList'] as $sk => $sv) {
                //$sheet->getRowDimension($row)->setRowHeight(22);

                $sheet->setCellValueExplicit('F' . $row, arrayGet($sv, 'name', ''), 's');
                $sheet->setCellValueExplicit('G' . $row, arrayGet($sv, 'material_sku', ''), 's');
                $sheet->setCellValueExplicit('H' . $row, arrayGet($sv, 'supplier', ''), 's');
                $sheet->setCellValueExplicit('I' . $row, arrayGet($sv, 'model', ''), 's');

                // 单件用量
                $sheet->setCellValueExplicit('J' . $row, $sv['material_dosage'], 'n');
                // 批色时间
                //$sheet->setCellValueExplicit('J' . $row, $sv['caigou_over_time'] > 0 ? date('Y-m-d H:i:s', $sv['caigou_over_time']) : 's');
                if ($sv['caigou_over_time'] > 0) {
                    $phpExcel->getActiveSheet()->setCellValue('K' . $row, $objDate::PHPToExcel($sv['caigou_over_time']));
                    $phpExcel->getActiveSheet()->getStyle('K' . $row)->getNumberFormat()->setFormatCode($objFormat::FORMAT_DATE_XLSX22);
                } else {
                    $sheet->setCellValueExplicit('K' . $row, '');
                }
                // 采购量
                $sheet->setCellValueExplicit('L' . $row, round($v['quantity'] * $sv['material_dosage'], 2), 'n');

                // 采购单位
                $sheet->setCellValueExplicit('M' . $row, arrayGet($sv, 'purchasing_unit', ''), 's');

                // 单价
                $sheet->setCellValueExplicit('N' . $row, $sv['caigou_unitprice'], 'n');

                // 实际采购量
                $sheet->setCellValueExplicit('O' . $row, $sv['shiji_caigou_count'], 'n');

                // 条数
                $sheet->setCellValueExplicit('P' . $row, $sv['tiaoshu'], 'n');
                $row++;
            }
            $n++;
        }

        // Rename worksheet
        $sheet->setTitle('worksheet');

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');

        $objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit();
    }

    /**
     * 开始采购面里料
     *
     *
     * @author KING
     * @date 2020年6月3日
     *
     */
    public function startPurchasing()
    {
        $materialId = $this->request->param('material_id/d', 0);
        $orderId = $this->request->param('order_id/d', 0);

        db('order_material')->where(['order_id' => $orderId, 'material_id' => $materialId])->update(['is_caigou_start' => 1, 'caigou_start_time' => time()]);

        return $this->Json(1);
    }

    /**
     * 物料详情
     *
     * @date 2020年11月6日
     *
     */
    public function makeTagLog()
    {
        $mid = $this->request->param('mid/d', '');
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $orderMaterialService = new OrderMaterialService();
            $materialService = new MaterialService();
            $orderMaterialItemService = new OrderMaterialItemService();
            $clientOrdernum = $this->request->param('client_ordernum/s');
            $name = $this->request->param('name/s', '');
            $caigouConfirmTime = $this->request->param('caigou_confirm_time/s', '');
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $export = $this->request->param('export/d', 0);
            $where = $data = [];
            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
            }
            if ($clientOrdernum != "") {
                $where[] = ['client_ordernum', 'like', "%" . $clientOrdernum . "%"];
            }
            if ($name != "") {
                $subQuery = db('material')->where('name', 'like', "%" . $name . "%")->distinct(true)->field('id')->buildSql();
                $where[] = ['material_name', 'like', "%" . $name . "%"];
            }
            if ($caigouConfirmTime != "") {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $caigouConfirmTime));
                $where[] = ['create_time', 'between', [$startTime, $endTime + 86399]];
            }
            if ($mid != "") {
                $where[] = ['order_material_id', '=', $mid];
            }
            $order = "id desc";
            $omInfo = db('order_material_log')->where($where)->page($page)->limit($limit)->order($order)->select();
            if (!empty($omInfo)) {
                foreach ($omInfo as $k => $v) {
                    $v['stalls_name'] = arrayGet(getStallsKV(), $v['stalls_id'], '');
                    $v['is_from_stock_name'] = $v['is_from_stock'] == 0 ? '否' : '是';
                    $data['data'][] = $v;
                }
            }
            //导出
            if ($export) {
                $this->_exportMakeTagXls('打标日志-' . date('YmdHis'), $data['data']);
                exit;
            }
            $data['count'] = db('order_material_log')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';

            return json($data);
        }

        $assign = [
            'mid' => $mid
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 来料退料记录
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function materialLog()
    {
        $mid = $this->request->param('mid/d', 0);
        if ($this->request->isAjax()) {
            $orderMaterialService = new OrderMaterialService();
            $omInfo = $orderMaterialService->getInfoById($mid);
            $orderId = arrayGet($omInfo, 'order_id', 0);
            $materialId = arrayGet($omInfo, 'material_id', 0);

            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $offset = ($page - 1) * $limit;

            $sql = "(SELECT 1 as ct,type,tiaoshu, cloth_num,create_time as time FROM " . config('database.prefix') . "order_material_log WHERE order_id={$orderId} AND material_id={$materialId})";
            $sql .= "UNION All (SELECT 2 as ct,mrl.type,1 as tiaoshu,mr.cloth_num,mrl.create_time FROM " . config('database.prefix') . "material_return_log mrl
			LEFT JOIN " . config('database.prefix') . "material_return mr ON mrl.material_return_id=mr.id
			WHERE mr.order_id={$orderId} AND mr.material_id={$materialId})";
            $res = db()->query("SELECT COUNT(*) as num FROM ({$sql}) tb");
            $data['count'] = $res ? $res[0]['num'] : 0;
//            echo "SELECT ct,type,tiaoshu,cloth_num,time FROM ({$sql}) tb ORDER BY time DESC LIMIT {$offset},{$limit}";die;
            $list = db()->query("SELECT ct,type,tiaoshu,cloth_num,time FROM ({$sql}) tb ORDER BY time DESC LIMIT {$offset},{$limit}");

            $data['data'] = $list;
            $data['code'] = 0;
            $data['msg'] = '';

            return json($data);
        }

        $assign = [
            'mid' => $mid
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 修改字段
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/8
     */
    public function editUnit()
    {
        $param = [
            'id' => $this->request->param('id/d', 0),
            'field' => trim($this->request->param('field/s', '')),
            'value' => trim($this->request->param('value/s', '')),
        ];
        switch ($param['field']) {
            case 'caigou_remark':
            case 'remark_approval_color':
                $temp = db('order')->where([
                    ['id', '=', $param['id']],
                ])->update([
                    $param['field'] => $param['value'],
                ]);
                if ($temp == 1) {
                    switch ($param['field']) {
                        case 'caigou_remark':
                            $this->addOrderLog($param['id'], '', "保存采购备注[{$param['value']}]");
                            break;
                        case 'remark_approval_color':
                            $this->addOrderLog($param['id'], '', "保存批色备注[{$param['value']}]");
                            break;
                    }
                    return $this->Json(1, '修改成功', $temp);
                }
                return $this->Json(10, '修改失败', $temp);
                break;
        }
        return $this->Json(10, '修改失败');
    }

    /**
     *
     * 设置采购执行人
     *
     * @author KING
     * @date 2020年7月15日
     *
     */
    public function setCaigouUser()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $caigouUserId = $this->request->param('caigou_user_id/d', 0);
        $upData = [
            'caigou_user_id' => $caigouUserId,
            'update_time' => time(),
        ];
        $ret = db('order')->where('id', $orderId)->update($upData);
        $systemUserKv = getSystemUserKV(null);
        $this->addOrderLog($orderId, '', "设置采购执行人为[" . arrayGet($systemUserKv, $caigouUserId, '') . "]");
        if ($ret) {
            return $this->Json(1, '设置采购执行人成功');
        } else return $this->Json(0);
    }

    /**
     * 查询统计信息
     * 订单时效
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/12
     */
    public function statistics()
    {
        $param = [
            'type' => $this->request->param('type/s', 'order_shixiao'),
        ];
        $purchasingService = (new PurchasingService());
        $res = $purchasingService->statistics_order_shixiao($param);
        return $this->Json(0, '', $res);
    }

    /**
     * 查询统计信息--订单详情
     * 订单时效
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/19
     */
    public function statistics_deatail()
    {
        $param = [
            'type' => $this->request->param('type/s', 'order_shixiao'),
            'num' => trim($this->request->param('num/d', 0)),
            'day' => trim($this->request->param('day/d', 0)),
            'page' => $this->request->param('page/d', 1),
            'limit' => $this->request->param('limit/d', 20),
        ];
        //2,数据查询
        if ($this->request->isAjax()) {
//            $page = $this->request->param('page/d', 1);
//            $limit = $this->request->param('limit/d', 20);
            $purchasingService = (new PurchasingService());
            $res = $purchasingService->statistics_deatail($param);
            $data['data'] = $res['data'];
            $data['count'] = $res['count'];
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $this->assign('param', $param);
        return $this->fetch('statistics_deatail');
    }

    /**
     * 保存采购成本备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function costRemark()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $remark = $this->request->param('remark/s', '');
        $upData = [
            'caigou_cost_remark' => $remark,
            'update_time' => time(),
        ];
        $ret = db('order')->where('id', $orderId)->update($upData);
        $this->addOrderLog($orderId, '', "保存采购成本备注[{$remark}]");
        if ($ret) {
            return $this->Json(1, '保存采购成本备注成功');
        } else return $this->Json(0);
    }

    /**
     * 保存采购核价备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function caigouPricing()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $remark = $this->request->param('remark/s', '');
        $upData = [
            'caigou_pricing' => $remark,
            'update_time' => time(),
        ];
        $ret = db('order')->where('id', $orderId)->update($upData);
        $this->addOrderLog($orderId, '', "保存采购核价备注[{$remark}]");
        if ($ret) {
            return $this->Json(1, '保存采购核价备注成功');
        } else return $this->Json(0);
    }

    /**
     * 异步计算小计金额
     *
     * @author King
     * @date 2021年7月21日
     *
     */
    public function getCaigouSubtotalMoney()
    {
        $mid = $this->request->param('mid/d', 0);
        $caigouUnitprice = $this->request->param('caigou_unitprice/f', 0);
        $billingCaigouCountOri = $this->request->param('billing_caigou_count_ori/f', 0);

        $orderMaterialService = new OrderMaterialService();
        $stallFeedService = new StallFeedService();

        $omInfo = $orderMaterialService->getInfoById($mid);
        $sfList = $stallFeedService->getListByMid($mid);

        $caigouSubtotalMoney = round($caigouUnitprice * $billingCaigouCountOri, 2);
        foreach ($sfList as $key => $value) {
            if ($value['original'] == 1) continue; // 初单的金额无需再次计入
            $billingCaigouCountFeed = floatval($value['billing_caigou_count_feed']);
            $caigouSubtotalMoney = ($value['caigou_unitprice'] * $billingCaigouCountFeed) + $caigouSubtotalMoney;
        }

        $result = [
            'caigouSubtotalMoney' => round($caigouSubtotalMoney, 2),
            'billingCaigouCount' => $omInfo['billing_caigou_count'] - $omInfo['billing_caigou_count_ori'] + $billingCaigouCountOri,
        ];
        return $this->Json(1, '操作成功', $result);

    }

    /**
     * 采购成本审核
     *
     * @throws \Exception
     * @author KING
     * @date 2020年7月31日
     *
     */
    public function costCheck()
    {
        $mid = $this->request->param('mid/d', 0);
        $stall_id = $this->request->param('stall_id/d', 0);
        $orderService = new OrderService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        try {
            db()->startTrans();

            // 记录原始开单采购数
            $omInfo = $orderMaterialService->getInfoById($mid);
            if (empty($omInfo)) {
                throw new \Exception('数据异常');
            }

            $oud = [
                'update_time' => time(),
                'caigou_cost_status' => 1,
                'caigou_cost_over_time' => time(),
            ];

            $orderId = $omInfo['order_id'];

            $res = db('order_material')->where('mid', $mid)->update($oud);
            $orderInfo = $orderService->getInfoById($orderId);
            if ($orderInfo['status'] == 0) $orderData['status'] = 1;
            $orderData['update_time'] = time();

            // 采购成本是否全部确认
            if ($orderInfo['o_type'] == 'FOB') {
                $orderMaterialInfo = db('order_material')->where("order_id = {$orderId} and caigou_cost_status = 0")->field('mid')->findOrEmpty();
            } elseif ($orderInfo['o_type'] == 'CMT2') {
                $orderMaterialInfo = db('order_material om')->join('material m', 'om.material_id = m.id')->where('m.type', 'accessories')->where(['om.order_id' => $orderId, 'om.caigou_cost_status' => 0])->field('om.mid')->findOrEmpty();
            } else $orderMaterialInfo = false;

            if (!$orderMaterialInfo) {
                $orderData['caigou_cost_status'] = 1;
            }

            // 采购合计金额
            $orderData['caigou_total_money'] = $orderMaterialService->getAllCaigouSubtotalMoney($orderId);
            db('order')->where('id', $orderId)->update($orderData);
            $nomInfo = $orderMaterialService->getInfoById($mid);
            $sfData = [
                'billing_caigou_count_feed' => $nomInfo['billing_caigou_count_ori'],
                'order_material_id' => $mid,
                'stall_id' => $stall_id,
                'caigou_unitprice' => $nomInfo['caigou_unitprice'],
                'billing_caigou_kgcount' => $nomInfo['billing_caigou_kgcount'],
                'billing_caigou_kgprice' => $nomInfo['billing_caigou_kgprice'],
                'order_id' => $nomInfo['order_id'],
                'client_ordernum' => $nomInfo['client_ordernum'],
                'material_id' => $nomInfo['material_id'],
                'status' => 1,
                'stall_order_time' => $nomInfo['stall_order_time'],
                'stall_order' => $nomInfo['stall_order'],
                'settle_unitprice' => min([$nomInfo['caigou_unitprice'], $nomInfo['customer_price']]),
                'original' => 1,
                'admin_id' => ADMIN_ID,
                'update_time' => time(),
                'create_time' => time(),
            ];
            $sfData['settle_amount'] = round($sfData['settle_unitprice'] * abs(floatval($sfData['billing_caigou_count_feed'])), 2);
            db('stall_feed')->insert($sfData);

            $this->addOrderLog($orderId, $omInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]采购成本通过审核");

            db()->commit();
            return $this->Json(1);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 采购成本补料
     *
     * @author KING
     * @date 2020年7月31日
     *
     */
    public function costFeed()
    {
        $mid = $this->request->param('mid/d', 0);
        $number = $this->request->post('number/f', 0); // 补料
        $billingCaigouKgcount = $this->request->post('billing_caigou_kgcount/f', 0); // 开单公斤数
        $orderService = new OrderService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $stallFeedService = new StallFeedService();
        try {
            db()->startTrans();

            $omInfo = $orderMaterialService->getInfoById($mid);
            if (empty($omInfo)) {
                throw new \Exception('数据异常');
            }

            $orderId = $omInfo['order_id'];

            $billingCaigouCount = $omInfo['billing_caigou_count'] + $number;

            //新增补退明细表记录
            $omiList = $orderMaterialItemService->getListByOrderMaterialId($mid, "stalls_id");
            if ($omiList) $sfData['stall_id'] = $omiList[0]['stalls_id'];
            $sfData = [
                'billing_caigou_count_feed' => $number >= 0 ? '+' . abs($number) : $number,
                'billing_caigou_kgcount' => $billingCaigouKgcount,
                'order_material_id' => $mid,
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'material_id' => $omInfo['material_id'],
                'admin_id' => ADMIN_ID,
                'update_time' => time(),
                'create_time' => time(),
            ];
            db('stall_feed')->insert($sfData);
            //同时更新order_material和order
            $sfList = $stallFeedService->getListByMid($omInfo['mid']);
            $caigouSubtotalMoney = $omInfo['caigou_unitprice'] * $omInfo['billing_caigou_count_ori'];
            foreach ($sfList as $key => $value) {
                $caigouSubtotalMoney = $caigouSubtotalMoney + ($value['caigou_unitprice'] * $value['billing_caigou_count_feed']);
            }
            $oud = array(
                'update_time' => time(),
                'billing_caigou_count_feed' => $omInfo['billing_caigou_count_feed'] . ($number >= 0 ? '+' . abs($number) : $number),
                'billing_caigou_count' => $billingCaigouCount,
                'caigou_subtotal_money' => round($caigouSubtotalMoney, 2),
            );
            $res = db('order_material')->where('mid', $mid)->update($oud);
            $orderInfo = $orderService->getInfoById($orderId);
            if ($orderInfo['status'] == 0) $orderData['status'] = 1;
            $orderData['update_time'] = time();

            // 采购合计金额stallFeedDetail
            $orderData['caigou_total_money'] = $orderMaterialService->getAllCaigouSubtotalMoney($orderId);
            db('order')->where('id', $orderId)->update($orderData, "id = " . $orderId);
            $this->addOrderLog($orderId, $orderInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]补料" . $number);

            db()->commit();
            $res = [
                'order_id' => $orderId,
                'billing_caigou_count' => $billingCaigouCount,
                'caigou_subtotal_money' => $caigouSubtotalMoney,
                'caigou_total_money' => $orderData['caigou_total_money']
            ];
            return $this->Json(1, '', $res);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 采购面板
     *
     * @return string
     * @author KING
     * @date 2020年7月1日
     *
     */
    public function panel()
    {
        if ($this->request->isPost()) {
            $createDate = $this->request->param('date/s', '');
            if (!isDateTime($createDate, 'Y-m-d')) $createDate = '';

            $where = [];
            $where[] = ['caigou_status', '=', 0];
            $where[] = ['status', 'in', [0, 1]];
            //订单加一级
            order_level($where, '');
            if ($createDate != '') {
                $where[] = ['create_time', 'between', [strtotime($createDate . ' 00:00:00'), strtotime($createDate . ' 23:59:59')]];
            }
            $list = db('order')->where($where)->order('shipment_time asc')->select();
            $skus = array_column($list, 'sku');
            $skuKV = db('sku')->where('sku', 'in', $skus)->column('ori_pic', 'sku');
            $factoryOutgoKV = getFactoryOutgoKV(null);

            $key = 'caigou';
            $result = [
                $key . '_orders' => count($list),
                $key . '_items' => array_sum(array_column($list, 'quantity')),
            ];
            $memoService = new MemoService();
            foreach ($list as $v) {
                // 判断采购是否异常
                $exception = $memoService->getPurchasingException($v['id']);
                $result[$key][] = [
                    'exception' => $exception,
                    'client_ordernum' => $v['client_ordernum'],
                    'sku' => $v['sku'],
                    'quantity' => $v['quantity'],
                    'shipment_time' => date("Y-m-d", $v['shipment_time']),
                    'factory_outgo_name' => arrayGet($factoryOutgoKV, $v['factory_outgo_id'], ''),
                    'pic' => arrayGet($skuKV, $v['sku'], ''),
                    'tags' => getOrderTag($v),
                ];
            }

            return $this->Json(1, '', $result);
        }

        return $this->fetch();
    }

    /**
     * 新增采购任务--页面显示
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/15
     */
    public function addCaigou()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $name = $this->request->param('name/s');
            $color = $this->request->param('color/s');
            $materialSku = $this->request->param('material_sku/s');
            $sku = $this->request->param('sku/s');
            $clientOrdernum = $this->request->param('client_ordernum/s');
            $supplier = $this->request->param('supplier/s');
            if ($supplier != '') {
                $where[] = ['supplier', 'like', "%{$supplier}%"];
            }
            if ($name != '') {
                $where[] = ['name', 'like', "%{$name}%"];
            }
            if ($color != '') {
                $where[] = ['color', 'like', "%{$color}%"];
            }
            if ($materialSku != '') {
                $where[] = ['material_sku', '=', $materialSku];
            }
            if ($clientOrdernum != '') {
                $where[] = ['id', 'in', db('order_material')->where('client_ordernum', $clientOrdernum)->column('material_id')];
            }
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order o')->field('o.id')->join('order_material om', "o.id=om.order_id", 'left')->where([['o.ext_id', '=', $ext_id]])->column('om.material_id');
                        $where[] = ['id', 'in', $temp];
                    }
                    break;
            }
            if ($sku != '') {
                $where[] = ['id', 'in', db('sku_material')->where('sku_id', db('sku')->where('sku', $sku)->column('id'))->column('material_id')];
            }

            $order = 'use_time desc';
            $data['data'] = db('material')->where($where)->page($page)->limit($limit)->order($order)->select();
            $days30 = time() - 30 * 86400;
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['use_orders'] = db('material_log')->where('material_id', $v['id'])->count();
                $data['data'][$k]['use_orders_30d'] = db('material_log')->where('material_id', $v['id'])->where('update_time', '>=', $days30)->count();
            }

            $data['count'] = db('material')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $this->assign('formData', []);
        return $this->fetch();
    }

    /**
     * 新增采购任务--获取材料信息
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/16
     */
    public function getCaigouMaterialInfo()
    {
        $material_id = $this->request->param('material_id/d', 0);
        $info = db('material m')
            ->field("m.*
            ,s.pic as s_pic,s.ori_pic
            ")
            ->join('sku_material sm', 'm.id=sm.material_id', 'left')
            ->join('sku s', 'sm.sku_id=s.id', 'left')
            ->where([
                ['m.id', '=', $material_id],
            ])->find();
        if (trim($info['pic']) == '') {
            $info['pic'] = $info['s_pic'];
        }
        $data['code'] = 0;
        $data['msg'] = '';
        $data['data'] = $info;
        return json($data);
    }
}
